0% found this document useful (0 votes)
12 views

Java New Syllabus Notes

The document provides a comprehensive overview of Java programming, covering key concepts of Object-Oriented Programming (OOP) such as classes, objects, inheritance, polymorphism, and abstraction. It details the structure of Java programs, including data types, operators, control statements, and exception handling, as well as advanced topics like multithreading and I/O streams. Additionally, it lists textbooks and references for further study in Java programming.

Uploaded by

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

Java New Syllabus Notes

The document provides a comprehensive overview of Java programming, covering key concepts of Object-Oriented Programming (OOP) such as classes, objects, inheritance, polymorphism, and abstraction. It details the structure of Java programs, including data types, operators, control statements, and exception handling, as well as advanced topics like multithreading and I/O streams. Additionally, it lists textbooks and references for further study in Java programming.

Uploaded by

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

JAVA PROGRAMMING

UNIT - I Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of


Object Oriented Programming – Differences between Procedure Oriented Programming and Object
Oriented programming - Benefits of OOPs – Application of OOPs. Java: History – Java features –
Java Environment – JDK – API. Introduction to Java: Types of java program – Creating and
Executing a Java program – Java Tokens- Java Virtual Machine (JVM) – Command Line Arguments
–Comments in Java program.
UNIT - II Elements: Constants – Variables – Data types - Scope of variables – Type casting –
Operators: Special operators – Expressions – Evaluation of Expressions. Decision making and
branching statements- Decision making and Looping– break – labeled loop – continue Statement.
Arrays: One Dimensional Array – Creating an array – Array processing – Multidimensional Array –
Vectors – ArrayList – Advantages of Array List over Array Wrapper classes.
UNIT - III Class and objects: Defining a class – Methods – Creating objects – Accessing class
members – Constructors – Method overloading – Static members –Nesting of Methods – this
keyword – Command line input. Inheritance: Defining inheritance –types of inheritance– Overriding
methods – Final variables and methods – Final classes – Final methods - Abstract methods and
classes – Visibility Control- Interfaces: Defining interface – Extending interface - Implementing
Interface - Accessing interface variables. Strings: String Array – String Methods – String Buffer
Class.
UNIT - IV Packages: Java API Packages – System Packages – Naming Conventions –Creating &
Accessing a Package – Adding Class to a Package – Hiding Classes. Exception Handling: Limitations
of Error handling – Advantages of Exception Handling - Types of Errors – Basics of Exception
Handling – try blocks – throwing an exception – catching an exception – finally statement.
Multithreading: Creating Threads – Life of a Thread – Defining & Running Thread – Thread Methods
– Thread Priority – Synchronization –Implementing Runnable interface – Thread Scheduling.
UNIT - V I/O Streams: File – Streams – Advantages - The stream classes – Byte streams –
Character streams. Applets: Introduction – Applet Life cycle – Creating & Executing an Applet –
Applet tags in HTML – Parameter tag – Aligning the display - Graphics Class: Drawing and filling
lines – Rectangles – Polygon – Circles – Arcs – Line Graphs – Drawing Bar charts AWT Components
and Even Handlers: Abstract window tool kit – Event Handlers – Event Listeners – AWT Controls
and Event Handling: Labels – Text Component – Action Event – Buttons – Check Boxes – Item
Event – Choice– Scrollbars – Layout Managers- Input Events – Menus.

TEXT BOOKS:
1. E. Balagurusamy, “Programming with Java”, TataMc-Graw Hill, 5th Edition.
2. Sagayaraj, Denis, Karthick and Gajalakshmi, “Java Programming for Core and advanced learners”,
Universities Press (INDIA) Private Limited 2018.

REFERENCES:
1. Herbert Schildt, “The complete reference Java”, TataMc-Graw Hill, 7th Edition.
UNIT - I : Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of
Object Oriented Programming – Differences between Procedure Oriented Programming and Object
Oriented programming - Benefits of OOPs – Application of OOPs. Java: History – Java features –
Java Environment – JDK – API. Introduction to Java: Types of java program – Creating and
Executing a Java program – Java Tokens- Java Virtual Machine (JVM) – Command Line Arguments
–Comments in Java program.

INTRODUCTION TO OOPS
OOPs refer to languages that use objects in programming. Object-oriented programming
aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming.
The main aim of OOP is to bind together the data and the functions that operate on them so that no
other part of the code can access this data except that function.
Object-oriented programming is concerned with isolating concepts of a problem domain into
separate entities and then using those entities to solve problems. Concepts related to a problem can
only be considered once they've been identified. In other words, we can form abstractions from
problems that make those problems easier to approach.
In Java, everything is based on the object. Java has a root class called Object from which the entire
functionality of Java is derived.

PARADIGMS OF PROGRAMMING LANGUAGE


A programming paradigm is a way of thinking about and structuring a program's
functionality. Programming paradigms differ from one another, for example in how the program's
execution and control are defined and what components the programs consist of.
Most programming languages that are currently in use support multiple programming paradigms.
Part of a programmer's growth involves the ability, through experience, to choose the appropriate
programming language and paradigm; there currently is no single ubiquitous programming
language and programming paradigm.
The most common programming paradigms today are object-oriented programming,
procedural programming, and functional programming.
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language or also
we can say it is a method to solve a problem using tools and techniques that are available to us
following some approach. There are lots for programming language that are known but all of them
need to follow some strategy when they are implemented and this methodology/strategy is
paradigms.

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING


Object-oriented programming is a method used for designing a program using classes and
objects. Object-oriented programming is also called the core of java. Object-oriented programming
organizes a program around objects and well-defined interfaces. This can also be characterized as
data controlling for accessing the code. In this type of approach, programmers define the data type
of a data structure and the operations that are applied to the data structure. This implies software
development and maintenance by using some of the concepts:
Object Inheritance
Class Polymorphism
Abstraction Encapsulation
OOPs, concepts in java are to improve code readability and reusability by defining a Java program
efficiently. The main principles of object-oriented programming are abstraction, encapsulation,
inheritance, and polymorphism. These concepts aim to implement real-world entities in
programs.

1. OBJECT
Objects are always called as instances of a class. Objects are created from class in java or
any other languages. Objects are those that have state and behavior. Objects are abstract data types
(i.e., objects behavior is defined by a set of values and operations).
These objects always correspond to things found in the real world, i.e., real entities. So,
they are also called a run time entity of the world. These are self–contained which consists of
methods and properties which makes data useful. Objects can be both physical and logical data. It
contains addresses and takes up some space in memory. Some of the examples of objects are a
dog, chair, tree etc.
When we treat animals as objects, it has states like color, name, breed etc., and behaviors
such as eating, wagging the tail etc.
Suppose, we have created a class called My book, we specify the class name followed by
the object name, and we use the keyword new.

Example 1:
Public class Mybook {
int x=10;
Public static void main (String args []) {
Mybook Myobj= new Mybook ();
System.out.println(MyObj.x);
}
}

In the above example, a new object is created, and it returns the value of x which may be the
number of books.
Mybook Myobj= new Mybook ();
This is the statement used for creating objects.
System.out.println(Myobj.x);
This statement is used to return the value of x of an object.
We can also create multiple objects in the same class and we can create in one class and access it
in another class. This method is used for better organization of classes and always remember that
name of the java file and the class name remains the same.

Example 2:
The below example shows how multiple objects are created in the same class and how they
are accessed from another class.
Mybook.java
Public class Mybook
{
int x=10;
int y=8;
}
Count.java
Class Count
{
Public static void main (String [] args)
{
Mybook myobj1 = new myobj1();
Mybook myobj2 = new myobj2();
System.out.println (myobj1.x);
System.out.println (myobj2.y);
}
}
When this program is compiled, it gives the result as 10, 8 respectively.

2. CLASS
Classes are like object constructors for creating objects. The collection of objects is said to
be a class. Classes are said to be logical quantities. Classes don’t consume any space in the
memory. Class is also called a template of an object. Classes have members which can be fields,
methods and constructors. A class has both static and instance initializers.
A class declaration consists of:
1. Modifiers:Can be public or default access.
2. Class name: Initial letter.
3. Superclass: A class can only extend (subclass) one parent.
4. Interfaces: A class can implement more than one interface.
5. Body: Body surrounded by braces, { }.
A class keyword is used to create a class. A simplified general form of the class definition is given
below:
class classname {
type instance variable 1;
type instance variable 2;
//Statement of code here
type instance variable n;
type methodname 1 (parameter list) {
// body of method
}
type methodname 2 (parameter list) {
// body of method
}
type methodname n (parameter list) {
// body of method
}
}
The variables or data defined within a class are called as instance variables. Code is always
contained in the methods. Therefore, the methods and variables defined within a class are called
members of the class. All the methods have the same form as main () these methods are not
specified as static or public.

3. ABSTRACTION
Abstraction is a process which displays only the information needed and hides the
unnecessary information. We can say that the main purpose of abstraction is data hiding.
Abstraction means selecting data from a large number of data to show the information needed,
which helps in reducing programming complexity and efforts.
There are also abstract class and abstract methods. An abstract class is a type of class that
declares one or more abstract methods. An abstract method is a method that has a method
definition but not implementation. Once we have modeled our object using data abstraction, the
same sets of data can also be used in different applications—abstract classes, generic types of
behaviors and object-oriented programming hierarchy. Abstract methods are used when two or
more subclasses do the same task in different ways and through different implementations. An
abstract class can have both the methods, i.e., abstract methods and regular meth ods.
Now let us see an example related to abstraction.
Suppose we want to create a student application and ask to collect the information about the
student.
We collect the following information.
Name
Class
Address
Dob
Fathers name
Mothers name and so on.
We may not require every information that we have collected to fill the application. So, we select
the data that is required to fill the application. Hence, we have fetched, removed, and selected the
data, the student information from large data. This process is known as abstraction in oops
concept.
Example:
//abstract parent class
Abstract class animal {
//abstract method
public abstract void sound ( ) ;
}
Public class lion extends animal {
Public void sound ( ) {
System.out.println (“ roar “ );
}
public Static void main ( String args [ ] ) {
animal obj = new lion ( );
obj. sound ();
}
}
Output:
Roar

4. INHERITANCE
Inheritance is a method in which one object acquires/inherits another object’s properties,
and inheritance also supports hierarchical classification. The idea behind this is that we can create
new classes built on existing classes, i.e., when you inherit from an existing class, we can reuse
methods and fields of the parent class. Inheritance represents the parent-child relationship.
For example, a whale is a part of the classification of marine animals, which is part of class
mammal, which is under that class of animal. We use hierarchical classification, i.e., top -down
classification. If we want to describe a more specific class of animals such as mammals, they
would have more specific attributes such as teeth; cold-blooded, warm-blooded, etc. This comes
under the subclass of animals where animals come under superclass. The subclass is a class which
inherits properties of the superclass. This is also called a derived class. A superclass is a base class
or parental class from which subclass inherits properties.
We use inheritance mainly for method overriding and R:
To inherit a class, we use the extend keyword.

There are five types of inheritance single, multilevel, multiple, hybrid and hierarchical.

i)Single level
In this one class i.e., derived class inherits properties from its parental class. This enables
code reusability and also adds new features to the code. Example: class b inherits properties from
class a.
Class a is base or parental class and class b is derived class.

Syntax:
Class a {

}
Class b extends class a {

}

ii)Multilevel
This one class is derived from another class which is also derived from another class i.e.,
this class has more than one parental class, hence it is called multilevel inheritance.
Syntax:
Class a {
….
}
Class b extends class a {
….
}
Class c extends class b {

}

iii)Hierarchical level
In this one parental class has two or more derived classes or we can say that two or more
child classes has one parental class.

Syntax:
Class a {

}
Class b extends class a {
..
}
Class c extends class a {
..
}

iv)Hybrid inheritance
This is the combination of multiple and multilevel inheritance and in java multiple
inheritance is not supported as it leads to ambiguity and this type of inheritance can only be
achieved through interfaces.
Consider that class a is the parental or base class of class b and class c and in turn class b and class
c are parental or base class of class d. Class b and class c are derived classes from class a and class
d is derived class from class b and class c.
Following program creates a super class called add and a subclass called sub, uses extend keyword
to create a subclass add.

Example
// a simple example of inheritance
//create a superclass
Class Add {
int my;
int by;
void setmyby (int xy, int hy) {
my=xy;
by=hy;
}
}
/create a sub class
class b extends add {
int total;
void sum () {
public Static void main (String args [ ] ) {
b subOb= new b ( );
subOb. Setmyby (10, 12);
subOb. Sum ( ) ;
System.out.println(“total =” + subOb. Total);
}
}
It gives output as – total = 22

5. POLYMORPHISM
Polymorphism refers to many forms, or it is a process that performs a single action in
different ways. It occurs when we have many classes related to each other by inheritance.
Polymorphism is of two different types, i.e., compile-time polymorphism and runtime
polymorphism. One of the examples in Compile time polymorphism is that when we ove rload a
static method in java. Run time polymorphism is also called a dynamic method dispatch is a
method in which a call to an overridden method is resolved at run time rather than compile time. In
this method, the overridden method is always called through the reference variable. By using
method overloading and method overriding, we can perform polymorphism. Generally, the concept
of polymorphism is often expressed as one interface, multiple methods. This reduces complexity
by allowing the same interface to be used as a general class of action.

Example:
public class Bird {

Public void sound ( ) {
System.out.println ( “ birds sounds “ );
}
}
public class pigeon extends Bird {

@override
public void sound ( ) {
System.out.println( “ cooing ” ) ;
}
}
public class sparrow extends Bird ( ) {
….
@override
Public void sound ( ){
System.out.println( “ chirp ” ) ;
}
}
In the above example, we can see common action sound () but there are different ways to do the
same action. This is one of the examples which shows polymorphism.
Polymorphism in java can be classified into two types:
1.Static / Compile-Time Polymorphism
Compile-Time polymorphism in java is also known as Static Polymorphism. to resolved at
compile-time which is achieved through Method Overloading.
2.Dynamic / Runtime Polymorphism
Runtime polymorphism in java is also known as Dynamic Binding which is used to call to an
overridden method that is resolved dynamically at runtime rather than at compile-time.

6. ENCAPSULATION
Encapsulation is one of the concepts in OOPs concepts; it is the process that binds together
the data and code into a single unit and keeps both from being safe from outside interference and
misuse. In this process, the data is hidden from other classes and can be accessed only through the
current class’s methods. Hence, it is also known as data hiding. Encapsulation acts as a protective
wrapper that prevents the code and data from being accessed by outsiders. These are controlled
through a well-defined interface.
Encapsulation is achieved by declaring the variables as private and providing public setter and
getter methods to modify and view the variable values. In encapsulation, the fields of a class are
made read-only or write-only. This method also improves the re-usability. Encapsulated code is
also easy to test for unit testing.

Example:
class animal {
// private field
private int age;
//getter method
Public int getage ( ) {
return age;
}
//setter method
public void setAge ( int age ) {
this. Age = age;
}
}
class Main {
public static void main (String args []);
//create an object of person
Animal a1= new Animal ();
//change age using setter
A1. setAge (12);
// access age using getter
System.out.println(“ animal age is ” + a1. getage ( ) );
}
}
Output: Animal age is 12
In this example, we declared a private field called age that cannot be accessed outside of
the class.
To access age, we used public methods. These methods are called getter and setter methods.
Making age private allows us to restrict unauthorized access from outside the class. Hence this is
called data hiding.

DIFFERENCES BETWEEN PROCEDURE ORIENTED PROGRAMMING AND OBJECT


ORIENTED PROGRAMMING

Procedural Oriented Programming Object Oriented Programming

In procedural programming, program


is divided into small parts In object oriented programming, program is
called functions. divided into small parts called objects.

Procedural programming follows top Object oriented programming follows bottom


down approach. up approach.

There is no access specifier in Object oriented programming have access


procedural programming. specifiers like private, public, protected etc.

Adding new data and function is not


easy. Adding new data and function is easy.

Procedural programming does not


have any proper way for hiding data Object oriented programming provides data
so it is less secure. hiding so it is more secure.

In procedural programming, Overloading is possible in object oriented


overloading is not possible. programming.

In procedural programming, function In object oriented programming, data is more


is more important than data. important than function.

Procedural programming is based Object oriented programming is based on real


on unreal world. world.

Examples: C, FORTRAN,Pascal,
Examples: C++, Java, Python, C# etc.
Basic etc.

BENEFITS OF OOPS
 We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development
time and higher productivity,
 OOP language allows to break the program into the bit-sized problems that can be solved easily
(one object at a time).
 The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.
 OOP systems can be easily upgraded from small to large systems.
 It is possible that multiple instances of objects co-exist without any interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use of existing classes.
 Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
 The data-centered design approach enables us to capture more details of model in an
implementable form.
While it is possible to incorporate all these features in an OOP, their importance depends upon the
type of project and preference of the programmer. These technology is still developing and current
products may be superseded quickly.
Developing a software is easy to use makes it hard to build.

APPLICATION OF OOPS
The concepts of OOPs provide many benefits for the programmer to design an efficient program.
Due to its reusability feature, it is widely used in many areas. Some of the application areas of OOP
are as follows:
a. Real-time systems
b. Object-oriented database
c. Graphical user interface design in the Windows operating system.
d. Artificial intelligence and expert systems
e. Parallel programming
f. CAD/CAM software and in many areas.
Points to Remember:
1. Encapsulation, Abstraction, Inheritance, and Polymorphism are the main fundamental principles
(main pillars) of the OOPs concepts in Java.
2. Object oriented programming model is an extension of procedural programming. It designs the
computer program using classes and objects.
3. Java OOPs concepts provide several advantages such as security, reusability, effective
communication, developing complex software, maintenance, and efficiency.

JAVA: HISTORY
James Gosling pioneered Java in June 1991 as a project called ‘Oak.’ Gosling aimed to
develop a virtual machine and language with a well-known notation like C, but with more precision
and simplicity than C/C++. In 1995, Java 1.0 was the first public execution. It pledged ‘Write Once,
Run Anywhere’ on popular platforms with free runtimes. It was very safe and configurable with
security that restricted network and file access. In a stable ‘applet’ setup, the significant web browsers
soon implemented it in their standard settings.
In 1997, Sun reached out to the ISO/IEC JTC1 and then Ecma International to formalize Java, but
they quickly withdrew. Java continues to be a de facto proprietary standard regulated by the Java
Community Process. With the revenue generated by new vision such as the Java Enterprise
Framework, Sun made several Java implementations free of charge. The critical difference is that the
compiler is not present in the JRE, which differentiates between its Software Development Kit (SDK)
and JRE (JRE).

JAVA FEATURES
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing and
ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner
way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java can be easily extended as it
is based on Object Model. Following are some basic concept of OOP's.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error
checking and runtime checking. But the main areas which Java improved were Memory Management
and mishandled Exceptions by introducing automatic Garbage Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform specific
machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent and
can be run on any machine, plus this bytecode format also provide security. Any machine with Java
Runtime Environment can run Java Programs.

5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us to
develop virus free, temper free system. Java program always runs in Java runtime environment with
almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks simultaneously.
Benefit of multithreading is that it utilizes same memory and other resources to execute multiple
threads at the same time, like While typing, grammatical errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features. Everything
related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But,
Java enables high performance with the use of just-in-time compiler.
10) Distributed
Java is also a distributed language. Programs can be designed to run on computer networks. Java has a
special class library for communicating using TCP/IP protocols. Creating network connections is very
much easy in Java as compared to C/C++.

JAVA ENVIRONMENT
The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer’s
operating system software and provides the class libraries and other resources that a specific.
Java program needs to run.
The JRE is one of three interrelated components for developing and running Java programs. The other
two components are as follows:
 The Java Development Kit, or JDK, is a set of tools for developing Java applications.
Developers choose JDKs by Java version and by package or edition—Java Enterprise
Edition (Java EE), Java Special Edition (Java SE), or Java Mobile Edition (Java ME). Every
JDK always includes a compatible JRE, because running a Java program is part of the
process of developing a Java program.
 The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a
default JRE, but developers are free to choose another that meets the specific resource needs
of their applications.
The JRE combines Java code created using the JDK with the necessary libraries required to run it on a
JVM and then creates an instance of the JVM that executes the resulting program. JVMs are available
for multiple operating systems, and programs created with the JRE will run on all of them. In this
way, the Java Runtime Environment is what enables a Java program to run in any operating system
without modification.

INTRODUCTION TO JAVA
TYPES OF JAVA PROGRAM
There are two types of Java programs.
1. Java Stand-Alone Applications
2. Java Applets.
Java stand alone applications: A stand alone application refer to a java program that can run
independently on a computer. Acrobat Reader is an excellent example of this type of application.
Every stand alone application begins its execution with the main() method. Java stand alone
applications can be classified into two types: a) console based applications b) Graphical User
Applications
Java Applets: java applets are java applications that run within a web browser. They are mainly used
for internet programming. The applet is capable of performing many tasks on a web page, such as
displaying graphics, playing sounds and accepting user input.

CREATING AND EXECUTING A JAVA PROGRAM

Step 1:
Write a program on the notepad and save it with .java (for example, DemoFile.java) extension.
class DemoFile
{
public static void main(String args[])
{
System.out.println("Hello!");
System.out.println("Java");
}
}
Step 2:
Open Command Prompt.

Step 3:
Set the path and directory in which the .java file is saved. In our case, the .java file is saved in
W:\\java pgms
C:…..>w:
W:>cd java pgms
W:\java pgms>set path=”c:\program files\java\JDK1.5.0\bin”

Step 4:
Use the following command to compile the Java program. It generates a .class file in the same folder.
It also shows an error if any.
javac DemoFile.java

Step 5:
Use the following command to run the Java program.
java DemoFile

OUTPUT: Hello! Java

JAVA TOKENS
Types of Tokens
Java token includes the following:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the following
keywords:

01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp

Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the identifier
name must be different from the reserved keywords. There are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with
digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Some valid identifiers are:
PhoneNumber
PRICE
radius
a
a1
_phonenumber
$circumference
jagged_array
12radius //invalid

Literals: In programming literal is a notation that represents a fixed value (constant) in the source
code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals are as
follows:
o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type

Operators: In programming, operators are the special symbol that tells the compiler to perform a
special operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>


Separators: The separators in Java is also known as punctuators. There are nine separators in Java,
are as follows:
separator <= ; | , | . | ( | ) | { | } | [ | ]

o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional
array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The Java
compiler treats comments as whitespaces. Java provides the following two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.

COMMAND LINE ARGUMENTS


The java command-line argument is an argument i.e. passed at the time of running the java
program. The arguments passed from the console can be received in the java program and it can be
used as an input. So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

EXAMPLE
In this example, we are receiving only one argument and printing it. To run this java program, you
must pass at least one argument from the command prompt.
class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sree ram 1 2 3 abc
OUTPUT
sree
ram
1
2
3
abc
UNIT – II: Elements: Constants – Variables – Data types - Scope of variables – Type casting –
Operators: Special operators – Expressions – Evaluation of Expressions. Decision making and
branching statements- Decision making and Looping– break – labeled loop – continue Statement.
Arrays: One Dimensional Array – Creating an array – Array processing – Multidimensional Array –
Vectors – ArrayList – Advantages of Array List over Array Wrapper classes.

ELEMENTS
Constants
A constant is a value that cannot be altered by the program during normal execution, i.e., the value is
constant. When associated with an identifier, a constant is said to be “named,” although the terms
“constant” and “named constant” are often used interchangeably. This is contrasted with a variable,
which is an identifier with a value that can be changed during normal execution, i.e., the value is
variable.
Syntax:
const double PI = 3.14159;
A constant in Java is an unchangeable value give to a variable.
For example:
int AGE = 28;
public class ConstantExample
{
private static final int AGE = 28;
public static void main(String args[])
{
System.out.println("Age ="+AGE);
}
}

The final keyword:


A final keyword tells Java compiler that the change in value assign to the variable is not allowed.
Constant naming conventions:
Use Upper case letters, for spaces use underscores.
For example:
int AGE = 28;
public keyword with constant:
It says that other classes in same Java project able to access the constant.
private keyword with constant:
It says that other classes in same Java project not able to access the constant.
static keyword with constant:
It makes constant accessible inside main().

Variables
A variable is a container which holds the value while the Java program
is executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable.
It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory allocation
for static variables happens only once when the class is loaded in the memory.
Example
public class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output
10
10.0

DATA TYPES IN JAVA


Java is a statically typed language, i.e., variables must be declared before its use. Java has
two major categories of data:
Primitive Data Type:
It is the most fundamental data type. Java consists of 8 primitive data types:-
Boolean: It is used to store two types of values, i.e., true or false. This data type is commonly used
as a flag in code logic. The default value of the Boolean data type is false.
Code:
boolean flag=true;
Byte: It can store 8-bit signed two’s complement integer. The default value of a byte data type is 0.
The range lies between -128 to 127
Code:
byte num = 127;
Char: This data type is used to store a single 16-bit Unicode character. It stores just one character
in simple words, and the word Unicode is used because java uses the Unicode system, not the
ASCII system. The size of this data type is 16bits (2 bytes). It is declared like below:
char letter = 'a';
Int: It is a data type that stores 32 bit(4 bytes) two’s complement integer, i.e., its range lies within ( -
2^31 to 2^32 – 1). It is declared using the int keyword followed by the name of the variable.
Code:
int number = 21;
Short: Similar to ‘int,’ short is also used to store integer values but within 16-bit (2 bytes) signed
two’s complement. Its range lies within (-2^15 to 2^16-1). It is declared using the short keyword.
Code:
short numShort = 9;
Long: It is 64 bit two’s complement integer and its range lies within (-2^63 to2^64 – 1) i.e. ( -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,808). It is declared using the long keyword.
Code:
long numLong = 543;
Float: As the name indicates, it is a data type that holds data with more precision, i.e., floating-
point numbers. It is a single-precision 32-bit (4 bytes) IEEE754 floating-point. It is declared using
the float keyword.
Code:
float decimalNum = 8.213245f
Double: It is a double-precision 64-bit (8 bytes) IEEE754 floating point. It is declared using
the double keyword.
Code:
double d = 73.546;
Non-primitive Data Type:
Unlike primitive data types, which don’t have any associated method with them, non-
primitive data types have associated methods. It refers to the Objects. It is also called Object data
types or Reference Data Types.
Example:
String: It is a sequence of characters.
Example: String str = “Hello World!!”;
Array: Collection of similar types of elements.
Example: String[] technology = [‘Java’ , ‘C’ , ‘Python’]
Other examples of non-primitive data types are Class, Objects, and Interface.
Date Types Flow chart:
SCOPE OF VARIABLES
Scope is that area of the program where the variable is visible to a program and can be used
(accessible). i.e. the scope of variable determines its accessibility for other parts of program.
Java allows declaring variables within any block. A block defines a scope that starts with an opening
curly brace and ends with a closing curly brace.
There are three types of variables in java, depending on their scope:
 local variables
 instance variables
 class variables (static variables).
Scope of Local Variables in Java
When the local variable is created inside a method, constructor, or block, their scope only remains
within the method, block, or constructor.
They are visible only within the method, constructor, or block. As you exit from the method or block
then the scope of a local variable is destroyed.
We cannot access local variables from outside the method, constructor, or block.
We can not change their values from outside of the block.
Scope of Instance variables in Java
The scope of instance variables is inside the class. They are visible inside all the methods,
constructors, and from the beginning of its program block to the end of program block in the class.
Therefore, All the methods, constructors, and blocks inside the class can access instance variables.
Normally, it is recommended to make these variables private in the class.
However, the visibility of instance variables for the sub-classes can be given with the use of access
modifiers.
In the user-defined method (instance method), the instance variables can be accessed directly by
calling the variable name inside the class.
Within static methods and different classes, instance variables should be called using object reference
variable. It has the following general form:
Scope of Static variables
The scope of a static variable is within the class. All the methods, constructors, and blocks inside the
class can access static variables by using the class name.
The visibility of the static variable is similar to the instance variable. However, you can declare the
static variable as public so that it can be available for users of the class. You will learn more in detail
in the static chapter.

TYPE CASTING
The process of converting the value of one data type (int, float, double, etc.) to another data type is
known as typecasting.
In Java, there are 13 types of type conversion. However, in this tutorial, we will only focus on the
major 2 types.
1. Widening Type Casting
2. Narrowing Type Casting
Widening Type Casting
In Widening Type Casting, Java automatically converts one data type to another data type.

Example: Converting int to double


class Main
{
public static void main(String[] args)
{
// create int type variable
int num = 10;
System.out.println("The integer value: " + num);
// convert into double type
double data = num;
System.out.println("The double value: " + data);
}
}
Output
The integer value: 10
The double value: 10.0
Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.
In the case of Widening Type Casting, the lower data type (having smaller size) is converted
into the higher data type (having larger size). Hence there is no loss in data. This is why this type of
conversion happens automatically.

Narrowing Type Casting


In Narrowing Type Casting, we manually convert one data type into another using the
parenthesis.
Example: Converting double into an int
class Main
{
public static void main(String[] args)
{
// create double type variable
double num = 10.99;
System.out.println("The double value: " + num);

// convert into int type


int data = (int)num;
System.out.println("The integer value: " + data);
}
}
Output
The double value: 10.99
The integer value: 10

OPERATORS IN JAVA
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Output
10
12
12
10

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Output
15
5
50
2
0

Java Shift Operator Example: >> vs >>>


public class OperatorExample
{
public static void main(String args[])
{
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Output:
5
5
-5
1073741819

java Relational Operators


Relational operators are used to check the relationship between two operands. For example,
a< b; //checks a is less than b
Here, > operator is the relational operator. It checks if a is less than b or not.
It returns either true or false.
class Main
{
public static void main(String[] args)
{
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}

SPECIAL OPERATORS
Regular:
int i = 5;
i = i + 2;
System.out.println(i); // 7
With special operator:
int i = 5;
i += 2;
System.out.println(i); // 7
Both above examples are doing the exact same thing — adding 2 to our i variable.
Regular:
int i2 = 10;
i2 = i2 - 2;
System.out.println(i3); // 12int i4 = 10;
i4 = i4 / 2;
System.out.println(i4); // 5
With special operator:
int i2 = 10;
i2 -= 2;
System.out.println(i2); // 8int i3 = 4;
i3 *= 3;
System.out.println(i3); // 12int i4 = 10;
i4 /= 2;
System.out.println(i4); // 5

Java AND Operator Example: Logical && vs Bitwise &


The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public 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

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c); //true || true = true
System.out.println(a>b|a<c); //true | true = true

//|| vs |

System.out.println(a>b||a++<c); //true || true = true


System.out.println(a); //10 because second condition is not checked
System.out.println(a>b|a++<c); //true | true = true
System.out.println(a); //11 because second condition is checked
}
}
Output:
true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public 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

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.
Java Assignment Operator Example
public 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

JAVA EXPRESSIONS
A Java expression consists of variables, operators, literals, and method calls. To know more
about method calls, visit Java methods. For example,
int score;
score=60;
Here, score = 90 is an expression that returns an int.
Consider another example,
double a=2.2, b=3.4, result;
result=a+b-3.4;
Here, a + b - 3.4 is an expression.
Consider another example,
if(number1==number 2)
System.out.println(“Number 1 is larger than Number 2”);
Here, number1 == number2 is an expression that returns a boolean value. Similarly, "Number 1 is
larger than number 2" is a string expression.
Evaluation of Expressions
For evaluating an expression that carries multiple operations in it, we can perform the computation of
each operation one by one. However, in the query processing system, we use two methods for
evaluating an expression carrying multiple operations. These methods are:
1. Materialization
2. Pipelining
Materialization
In this method, the given expression evaluates one relational operation at a time. Also, each
operation is evaluated in an appropriate sequence or order. After evaluating all the operations, the
outputs are materialized in a temporary relation for their subsequent uses. It leads the materialization
method to a disadvantage. The disadvantage is that it needs to construct those temporary relations for
materializing the results of the evaluated operations, respectively. These temporary relations are
written on the disks unless they are small in size.
Pipelining
Pipelining is an alternate method or approach to the materialization method. In pipelining, it
enables us to evaluate each relational operation of the expression simultaneously in a pipeline. In this
approach, after evaluating one operation, its output is passed on to the next operation, and the chain
continues till all the relational operations are evaluated thoroughly. Thus, there is no requirement of
storing a temporary relation in pipelining. Such an advantage of pipelining makes it a better approach
as compared to the approach used in the materialization method. Even the costs of both approaches
can have subsequent differences in-between. But, both approaches perform the best role in different
cases. Thus, both ways are feasible at their place.

DECISION MAKING AND BRANCHING STATEMENTS


Decision making and branching
Generally a program executes it's statements from beginning to end. But not many programs
execute all their statements in strict order from beginning to end. Most programs decide what to do in
response to changing circumstances.
In a program statements may be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence,selection or iteration.
When a program breaks the sequential flow and jumps to another part of the code, it is
called selection or branching. When the branching is based on a particular condition, it is known
as conditional branching. If branching takes place without any condition, it is known as unconditional
branching. Java language supports two types of selections statements: if and switch. In addition, in
certain circumstances '?' operator can be used as an alternative to if statements.

DECISION MAKING WITH IF STATEMENT:


An if statement tests a particular condition; if the condition evaluates to true , a course of
action is followed i.e a statement or set of statements is executed . Otherwise (if the condition
evaluates to false), the course-of-action is ignored. The if statement may be implemented in different
forms depending on the complexity of conditions to be tested.
 Simple if statement
 if....else statement
 Nested if....else statement
 else if ladder
SIMPLE IF STATEMENT:
The syntax of the if statement is shown below:
if(expression)
statements;
Where a statement may consist of a single statement , a compound statement, or nothing. The
expression must be enclosed in parantheses. If the expression evaluates to true, the statement is
executed, otherwise ignored.
Following figure illustrates the if construct of java:

Example:
if(a>10)
if(b<15)
c=(a-b)*(a+b);
If the value of a is greater than 10, then the following statement is executed which in turn is another if
statement. This if statement tests b and if b is less than 15, then c is claculated.

THE IF....ELSE STATEMENT:


This form of if allows either-or condition by providing an else clause. The syntax of the if-else
statement is the following:
if(expression)
statement-1;
else
statement-2;
If the expression evaluates to true i.e., a non-zero value, the statement-1 is executed, otherwise
statement-2 is executed. The statement-1 and statement-2 can be a single statement, or a compound
statement, or a null statement.
Following figure illustrates the if else construct of java:

Example:
int a,b;
if(a<=b)
a=0;
else
b=0;
NESTED IF....ELSE STATEMENT:
A Nested if is an if that has another if in it's 'if's' body or in it's else's body. The nested if can
have one of the following three forms:
1. if(expression1)
{
if(expression2)
statement-1;
else
statement-2;
}
else
body of else;

2. if(expression1)
body-of-if;
else
{
if(expression2)
statement-1;
else
statement-2;
}

3. if(expression1)
{
if(expression2)
statement-1;
else
statement-2;
}
else
{
if(expression3)
statement-3;
else
statement-4;
}

THE ELSE-IF LADDER:


A common programming construct in the java is the if-else-if ladder , which is often also
called the if-else-if staircase because of it's appearence.
It takes the following general form:
if(expression1) statement1;
else
if(expression2) statement2;
else
if(expression3) statement3;
else statement n;
The expressions are evaluated from top downward. As soon as expression evaluates to true,
the statement associated with it is executed and the rest of the ladder is bypassed. If none of the
expression are true, the final else gets executed. If the final else is missing , no action takes place if all
other conditions are false.
Although it is technically correct to have indentation in the if-else-if ladder as shown above.
however, it generally leads to overly deep indentation . For this reason, the if-else-if ladder is
generally indented like this:
if(expression1) statement 1;
elseif(expression2) statement 2;
elseif(expression3) statement 3;
else statement n;

THE SWITCH STATEMENT:


Java provides a multiple branch selection statement known as switch. This selection statement
successively tests the value of an expression against a list of integer or character constants. When a
match is found, the statements associated with that constant are executed. The general form of switch
is:
switch(expression)
{
case value1:
Codesegment 1
case value2:
Codesegment 2
...
case valuen:
Codesegment n
default:
default Codesegment

A switch statement is used for multiple way selection that will branch to different code
segments based on the value of a variable or an expression . The optional default label is used to
specify the code segment to be executed when the value of the variable or expression does not match
with any of the case values. if there is no break statement as the last statement in the code segment
for a certain case, the execution will continue on into the code segment for the next case clause
without checking the case value.

DECISION MAKING AND LOOPING


The iteration statements aloow a set of instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called loops or looping statements. Java
provides three kinds of loops:
 While loop
 do-while loop
 for loop
All three constructs of java repeat a set of statements as long as a specified condition remains true.
The specified condition is generally referred to as a loop control. For all three loop statements, a true
condition is any nonzero value. A zero value indicates a false condition.

THE WHILE STATEMENT:


The most simple and general looping structure available in java is the while statement. The syntax of
while loop is:
while(condition)
{
//loop-body
}
Where the loop body may contain a single statement, a compound statement or an empty statement.
The loop iterates while the condition evaluates to true. When the expression becomes false, the
program control passes to the line after the loop body code.
//program for while loop
class whiletest
{
public static void main(String args[])
{
int n=10;
while(n>0)
{
System.out.println("tick",+n);
n--;
}
}
}

THE DO STATEMENT:
Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-
expression at the bottom of the loop after executing it's loop-body statements. This means that a do-
while loop always executes at least once.
The syntax of the do-while loop is:
do
{
loop-body;
}
while(condition);

Example:
Class doWhileCheck
{
public static void main (String args[])
{
int n=10;
do
{
System.out.println("tick"+n);
n--;
}
while(n>0);
}
}
THE FOR STATEMENT:
The for loop is the easiest to understand of the java loops. All its loop-control elements
are gathered in one place (on the top of the loop), while in the other loop construction of C++ ,
they( top-contol elements) are scattered about the program. The Syntax of the for loop
statement is:
for( initialization expression(s); test condition; update expression)
{
loop-body;
}
//program showing usage of for loop
class forTest
{
public static void main(String args[])
{
int i;
for( i=1; i<=10; i++)
System.out.println(i);
}
}
Following figure outlines the working of a for loop:

The break Statement


The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the
previous discussion of the switch statement. You can also use an unlabeled break to terminate
a for, while, or do-while loop, as shown in the following BreakDemo program:
class BreakDemo
{
public static void main(String[] args)
{
int[] arrayOfInts ={ 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt)
{
System.out.println("Foundsearchfor + " at index " + i);
}
else
{
System.out.println(searchfor + " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface,
terminates the for loop when that value is found. Control flow then transfers to the statement after
the for loop. This program’s output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but
a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is
similar to the previous program, but uses nested for loops to search for a value in a two-dimensional
array. When the value is found, a labeled break terminates the outer for loop (labeled “search”):
class BreakWithLabelDemo
{
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++)
{
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Foundsearchfor + " at " + i + ", " + j);
}
else
{
System.out.println(searchfor + " not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the
label. Control flow is transferred to the statement immediately following the labeled (terminated)
statement.

LABELED LOOP IN JAVA


A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the end.
Therefore, a loop with the label is called a labeled loop.
In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good habit to
label a loop when using a nested loop. We can also use labels with continue and break statements.
Java Labeled for Loop
Labeling a for loop is useful when we want to break or continue a specific for loop according to
requirement. If we put a break statement inside an inner for loop, the compiler will jump out from the
inner loop and continue with the outer loop again.
What if we need to jump out from the outer loop using the break statement given inside the inner
loop? The answer is, we should define the label along with the colon(:) sign before the loop.
Syntax:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}
Let's see an example of labeled for-loop.

LabeledForLoop.java
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
Output:
123456789
123456789
123456789
123456789
123456789

Labeled while Loop


Syntax:
labelName:
while ( ... )
{
//statements to execute
}
LabledWhileLoop.java
public class LabledWhileLoop
{
public static void main(String args[])
{
int i = 0;
whilelabel:
while (i < 5)
{
System.out.println("outer value of i= " + i);
i++;
forlabel:
for (int j = 0; j < 5; j++)
{
if (j > 0)
{
//execution transfer to the for loop
continue forlabel;
} //end of if
if (i > 1)
{
//execution transfer to the while loop
continue whilelabel;
} //end of if
System.out.println("inner value of i= " + i + ", j= " + j);
1. } //end of for
} //end of while
} //end of main
}
Output:
outer value of i= 0
inner value of i= 1, j= 0
outer value of i= 1
outer value of i= 2
outer value of i= 3
outer value of i= 4

The continue Statement


The continue statement skips the current iteration of a for, while , or do-while loop. The
unlabeled form skips to the end of the innermost loop’s body and evaluates the booleanexpression that
controls the loop. The following program, ContinueDemo , steps through a String, counting the
occurences of the letter “p”. If the current character is not a p, the continuestatement skips the rest of
the loop and proceeds to the next character. If it is a “p”, the program increments the letter count.
class ContinueDemo
{
public static void main(String[] args)
{
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
}
System.out.println("FoundnumPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When
you run the program again, the count will be wrong, saying that it found 35 p’s instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given
label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a
substring within another string. Two nested loops are required: one to iterate over the substring and
one to iterate over the string being searched. The following program,ContinueWithLabelDemo, uses
the labeled form of continue to skip an iteration in the outer loop.
class ContinueWithLabelDemo
{
public static void main(String[] args)
{
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
Here is the output from this program.
Found it

Arrays: One Dimensional Array


Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator. In Java, array is an object of a dynamically generated class. Java array
inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single Dimensional Array in Java

Syntax to Declare an Array in Java


dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
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;
//traversing 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

Declaration, Instantiation and Initialization of Java Array We can declare, instantiate and initialize the
java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//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
33
3
4
5
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
OUTPUT
123
245
445

VECTOR
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store
n-number of elements in it as there is no size limit. It is a part of Java Collection framework since
Java 1.2. It is found in the java.util package and implements the List interface, so we can use all the
methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't
need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform
better in such case.
The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it
fails and throws the ConcurrentModificationException.
It is similar to the ArrayList, but with two differences-
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections framework.
Java Vector class Declaration
public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable
Java Vector Constructors
Vector class supports four types of constructors. These are given below:
S.No Constructor Description
1) vector() It constructs an empty vector with the
default size as 10.
2) vector(int initialCapacity) It constructs an empty vector with the
specified initial capacity and with its
capacity increment equal to zero.
3) vector(int initialCapacity, It constructs an empty vector with the
int capacityIncrement) specified initial capacity and capacity
increment.
4) Vector( Collection<? It constructs a vector that contains the
extends E> c) elements of a collection c.

Java Vector Methods


The following are the list of Vector class methods:
SN Method Description
1) add() It is used to append the specified element in the given vector.
2) addAll() It is used to append all of the elements in the specified collection
to the end of this Vector.
3) addElement() It is used to append the specified component to the end of this
vector. It increases the vector size by one.
4) capacity() It is used to get the current capacity of this vector.
5) clear() It is used to delete all of the elements from this vector.
6) clone() It returns a clone of this vector.
7) contains() It returns true if the vector contains the specified element.
8) containsAll() It returns true if the vector contains all of the elements in the
specified collection.
9) copyInto() It is used to copy the components of the vector into the specified
array.
10) elementAt() It is used to get the component at the specified index.
11) elements() It returns an enumeration of the components of a vector.
12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if
necessary. It ensures that the vector can hold at least the number
of components specified by the minimum capacity argument.
13) equals() It is used to compare the specified object with the vector for
equality.
14) firstElement() It is used to get the first component of the vector.
15) forEach() It is used to perform the given action for each element of the
Iterable until all elements have been processed or the action
throws an exception.
16) get() It is used to get an element at the specified position in the
vector.
17) hashCode() It is used to get the hash code value of a vector.
18) indexOf() It is used to get the index of the first occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.
19) insertElementAt() It is used to insert the specified object as a component in the
given vector at the specified index.
20) isEmpty() It is used to check if this vector has no components.
21) iterator() It is used to get an iterator over the elements in the list in proper
sequence.
22) lastElement() It is used to get the last component of the vector.
23) lastIndexOf() It is used to get the index of the last occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.
24) listIterator() It is used to get a list iterator over the elements in the list in
proper sequence.
25) remove() It is used to remove the specified element from the vector. If the
vector does not contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are
present in the specified collection.
27) removeAllElements() It is used to remove all elements from the vector and set the size
of the vector to zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the
argument from the vector.
29) removeElementAt() It is used to delete the component at the specified index.
30) removeIf() It is used to remove all of the elements of the collection that
satisfy the given predicate.
31) removeRange() It is used to delete all of the elements from the vector whose
index is between fromIndex, inclusive and toIndex, exclusive.
32) replaceAll() It is used to replace each element of the list with the result of
applying the operator to that element.
33) retainAll() It is used to retain only that element in the vector which is
contained in the specified collection.
34) set() It is used to replace the element at the specified position in the
vector with the specified element.
35) setElementAt() It is used to set the component at the specified index of the
vector to the specified object.
36) setSize() It is used to set the size of the given vector.
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the
specified Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over
the elements in the list.
40) subList() It is used to get a view of the portion of the list between
fromIndex, inclusive, and toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this
vector in correct order.
42) toString() It is used to get a string representation of the vector.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current
size.
Example
import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}

OUTPUT
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the
traditional array. It is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so
we can use all the methods of List interface here. The ArrayList maintains the insertion order
internally.
It inherits the AbstractList class and implements List interface.
The important points about Java ArrayList class are:
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of
shifting needs to occur if any element is removed from the array list.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,
Serializable
Constructors of ArrayList
Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection<? It is used to build an array list that is initialized with the
extends E> c) elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a
list.
boolean addAll(Collection<? It is used to append all of the elements in the specified
extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity(int It is used to enhance the capacity of an ArrayList instance.
requiredCapacity)
E get(int index) It is used to fetch the element from the particular position
of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
Example
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Output:
[Mango, Apple, Banana, Grapes]

Advantages / Benefits of arraylist in java:


 We have some disadvantages of arrays like arrays are fixed in length. and we need to mention size of
the array while creation itself.
 So we have some advantages of arraylist when compared to arrays in java.
 Here the major advantages of arraylist over arrays.

1.ArrayList is variable length


 One of the major benefit of arraylist is it is dynamic in size. we can increase as well as decrease size
of the arraylist dynamically.
 Resizable.
2.Default initial capacity is 10.
 One of the major benefit of arraylist is by default it will assign default size as 10.
 Whenever we create object of ArrayList constructor of ArrayList assign default capacity as 10.

3.Insert and remove elements also at particular position of ArrayList


 Another advantage of ArrayList is it can add and remove elements at particular position.
4.Add any type of data into ArrayList.
 We can add different type of objects in to the ArrayList.
 In this scenario avoid mentioning generics while declaring ArrayList.
5.Traverse in both directions.
 We can traverse both direction using List Iterator.
6.ArrayList allows Multiple null values
 We can add multiple null elements to ArrayList
7.ArrayList allows to add duplicate elements
 We can add duplicate elements into arrayList
8.ArrayList has many methods to manipulate stored objects.
 ArrayList has many methods to manipulate stored objects.
 addAll(), isEmpty(). lastIndexOf() etc.
UNIT – III: Class and objects: Defining a class – Methods – Creating objects – Accessing class
members – Constructors – Method overloading – Static members –Nesting of Methods – this
keyword – Command line input. Inheritance: Defining inheritance –types of inheritance– Overriding
methods – Final variables and methods – Final classes – Final methods - Abstract methods and
classes – Visibility Control- Interfaces: Defining interface – Extending interface - Implementing
Interface - Accessing interface variables. Strings: String Array – String Methods – String Buffer
Class.

CLASSES AND OBJECTS


Java is an object-oriented programming language. Everything in Java is associated with
classes and objects, along with its attributes and methods. For example: in real life, a car is an object.
The car has attributes, such as weight and color, and methods, such as drive and brake.
Create a Class
To create a class, use the keyword class:
Example
Main.java
Create a class named "Main" with a variable x:
public class Main
{
int x = 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now we
can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj = new Main();
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used for better
organization of classes (one class has all the attributes and methods, while the other class holds
the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this example, we have
created two files in the same directory/folder:
 Main.java
 Second.java
Main.java
public class Main
{
int x = 5;
}
Second.java
class Second
{
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println(myObj.x);
}
}
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java
Run the Second.java file:
C:\Users\Your Name>java Second
output
5
METHODS AND METHOD DECLARATION IN JAVA
A method in Java is a block of statements that has a name and can be executed by calling (also
called invoking) it from some other place in your program. Along with fields, methods are one of the
two elements that are considered members of a class. (Constructors and initializers are not considered
class members.)
Every program must have at least one method for the program to accomplish any work. And every
program must have a method named main, which is the method first invoked when the program is
run.
All methods — including the main method — must begin with a method declaration. Here’s the basic
form of a method declaration:
visibility [static] return-type method-name (parameter-list)
{
Statements
}
The following list describes the method declaration piece by piece:
 visibility: The visibility of a method determines whether the method is available to other classes. The
options are
 public: Allows any other class to access the method
 private: Hides the method from other classes
 protected: Lets subclasses use the method but hides the method from other classes
 static: This optional keyword declares that the method is a static method, which means that you can
call it without first creating an instance of the class in which it’s defined. The main method must
always be static, and any other methods in the class that contains the main method usually should be
static as well.
 return-type: After the word static comes the return type, which indicates whether the method returns
a value when it is called — and if so, what type the value is. If the method doesn’t return a value,
specify void.
 If you specify a return type other than void, the method must end with a return statement that returns a
value of the correct type. For more information, see return Statement.
 method-name: Now comes the name of your method. The rules for making up method names are the
same as the rules for creating other identifiers: Use any combination of letters and numbers, but start
with a letter.
 parameter list: You can pass one or more values to a method by listing the values in parentheses
following the method name. The parameter list in the method declaration lets Java know what types
of parameters a method should expect to receive and provides names so that the statements in the
method’s body can access the parameters as local variables.
 statements: One or more Java statements that comprise the method body, enclosed in a set of braces.
Unlike Java statements such as if, while, and for, the method body requires you to use the braces even
if the body consists of only one statement.
ACCESSING CLASS MEMBERS
To access the members of a class,
 First of all, import the class.
 Create an object of that class.
 Using this object, access the members of that class.
Suppose there is a class in a package called myPackage with a method named display()
package myPackage;
public class Sample
{
public void display()
{
System.out.println("Hello");
}
}
You can access it as.
import myPackage;
public class MyClass
{
public static void main(String args[])
{
Sample s = new Sample();
s.done();
}
}
Output
Hello

CONSTRUCTORS IN JAVA
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object. Every time an object is created
using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java:
1. no-arg constructor
2. parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if
your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object creation.
In other words, we can have private, protected, public or default constructor in Java.
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obj
creation.
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output
Bike is created
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output
111 Karan
222 Aryan

METHOD OVERLOADING IN JAVA


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability
of the program
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of
the method because its name differs.
So, we perform method overloading to figure out the program quickly
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
1) Method Overloading: changing no. of arguments
In this example, 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
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type
The first add method receives two integer arguments and second add method receives two double
arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output
22
24.9

STATIC MEMBERS
In Java, static members are those which belongs to the class and you can access these members
without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword static. Static methods can
access only static fields, methods. To access static methods there is no need to instantiate the class,
you can do it just using the class name as −
Example
public class MyClass {
public static void sample(){
System.out.println("Hello");
}
public static void main(String args[]){
MyClass.sample();
}
}
Output
Hello
Static Fields − You can create a static field by using the keyword static. The static fields have the
same value in all the instances of the class. These are created and initialized when the class is loaded
for the first time. Just like static methods you can access static fields using the class name (without
instantiation).
Example
public class MyClass {
public static int data = 20;
public static void main(String args[]){
System.out.println(MyClass.data);
}
Java Arrays with Answers
27
}
Output
20
Static Blocks − These are a block of codes with a static keyword. In general, these are used to
initialize the static members. JVM executes static blocks before the main method at the time of class
loading.
Example
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Output
Hello this is a static block
This is main method

NESTING OF METHODS
A method of a class can be called only by an object of that class using the dot operator. So, there is an
exception to this. A method can be called by using only its name by another method of the same class
that is called Nesting of Methods.
Program
class test
{
int a,b;
test(int p, int q)
{
a=p;
b=q;
}
int greatest()
{
if(a>=b)
return(a);
else
return(b);
}
void display()
{
int great=greatest();
System.out.println("The Greatest Value="+great);
}
}
class temp
{
public static void main(String args[])
test t1=new test(25,24);
t1.display();
}
}
Output
The Greatest Value = 25

THIS KEYWORD
The this keyword refers to the current object in a method or constructor.
Example
Using this with a class attribute (x):
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
The most common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
this can also be used to:
 Invoke current class constructor
 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

COMMAND LINE INPUT


The most common use of the ‘this’ keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
this can also be used to:
 Invoke current class constructor
 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = reader.readLine();
// Printing the read line
System.out.println(name);
}}
Input:
Java
Output:
Java
To read other types, we use functions like Integer.parseInt(), Double.parseDouble().

2. Using Scanner Class


This is probably the most preferred method to take input. The main purpose of the Scanner class is
to parse primitive types and strings using regular expressions, however, it is also can be used to
read input from the user in the command line.

 Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
 Regular expressions can be used to find tokens.
 The reading methods are not synchronized
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " + s);
int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
// closing scanner
in.close();
}
}
Input
Numbers
12
3.4
Output:
You entered string Numbers
You entered integer 12
You entered float 3.4

3. Console Class
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is introduced
since 1.5.
code to get the instance of Console class.
Console c=System.console();
Java Console Example to read password
import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output
Enter password:
Password is: 123
4. Command line arguments
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.
So, it provides a convenient way to check the behavior of the program for the different values. You
can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Example:
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sri ram 1 3 abc
Output:
sri
ram
1
3
abc

INHERITANCE IN JAVA
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs(Object Oriented programming system). The idea
behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also. Inheritance represents
the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
o For Method overridding(so run time polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a
type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the 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...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so
there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){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...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, 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 the same method and you call it from child class object, there will be ambiguity to
call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error.
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

Method Overriding in Java


1. Understanding the problem without method overriding
2. Can we override the static method
3. Method overloading vs. method overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
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

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound with an object.
Static belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?


No, because the main is a static method.
Java Final Keyword, Variable, Method and Class
We know that there are 48 reserved keywords in Java and the final keyword is one of them. It is a
keyword that can be used with entities in Java to restrict their use. We can use it with class, methods,
variables.
There are different uses of the Java final keyword for different entities. That is, the purpose of using
the final keyword is different for class, variable, and method.
In this article, we will discuss the final keyword in Java and learn to implement and use it with
different parameters.

FINAL KEYWORD
Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we
initialize a variable with the final keyword, then we cannot modify its value.
If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a
class as final, we restrict the other classes to inherit or extend it.
In other words, the final classes can not be inherited by other classes.
This was a brief introduction to a final keyword in Java. Now we will discuss the implementation of
the final keyword with a variable, method, and class in Java.
FINAL VARIABLE
Once we declare a variable with the final keyword, we can’t change its value again. If we attempt to
change the value of the final variable, then we will get a compilation error.
Generally, we can consider a final variable as a constant, as the final variable acts like a constant
whose values cannot be changed.
This rule was for the normal variables, what if we declare the reference variables as final? The
restriction with the final reference variable is that we cannot change “what the object is referring to”
but we can modify the object itself.
We can’t just declare a variable as final without initializing it. That is, we have to give it an initial
value while declaring a final variable. If we declare the final variable without initialization, then it is a
blank final variable.
But it is mandatory to initialize a final variable either during declaration or after declaration. If we
leave it uninitialized, then we will get a compilation error.
package com.techvidvan.finalkeyword;
public class Vehicle {
//declaring and initializing a final variable
final int speedlimit = 60;
void controlSpeed() {
//Trying to change the value of the final variable will give an error
speedlimit = 150;
}
public static void main(String args[]) {
Vehicle obj = new Vehicle();
obj.controlSpeed();
}
}
Here, cannot assign a value to final variable ‘speedlimit’ as 150.
Output
. . .java:9: error: cannot assign a value to final variable speedlimit
speedlimit = 150;
^
1 error

FINAL METHOD
We can declare Java methods as Final Method by adding the Final keyword before the method name.
The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the Final
Method is to declare methods of how’s definition can not be changed by a child or subclass that
extends it.
package com.techvidvan.finalkeyword;
public class Parent {
final void final_method() {
//definition of the Final Method
}
}
public class Child extends Parent {
final void final_Method() // overriding the method from the parent class
{
// another definition of the final method
}
}
The above example of the Final Method generates a compile-time error.
As the Parent class Final method was overridden by the Child class Final method; that is not possible
in the Java programming language.
FINAL CLASS
We can also declare a class with a final keyword in Java. When we declare a class as final, then we
restrict other classes to inherit or extend it.
In short, Java final class can’t be extended by other classes in the inheritance. If another class attempts
to extend the final class, then there will be a compilation error.
final class Tech {
// methods and variables of the class Tech
}
class Vidvan extends Tech {
// COMPILE- TIME error as it extends final class
}
package com.techvidvan.finalkeyword;
public class Vidvan extends Tech {
void test() {
System.out.println("My Method");
}
public static void main(String[] args {
Vidvan obj = new Vidvan();
obj.test();
}
}
final class Tech {
//code inside class
}
Output
Compile time error
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential information to the
user. Abstraction can be achieved with either abstract classes or interfaces (which you will learn
more about in the next chapter). The abstract keyword is a non-access modifier, used for classes and
methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we
used in the Polymorphism chapter to an abstract class:
Example
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output
The pig says: wee wee
Zzz
VISIBILITY CONTROL
It is possible to inherit all the members of a class by a subclass using the keyword extends. The
variables and methods of a class are visible everywhere in the program. However, it may be necessary
in some situations we may want them to be not accessible outside. We can achieve this in Java by
applying visibility modifiers to instance variables and methods. The visibility modifiers are also
known as access modifiers. Access modifiers determine the accessibility of the members of a class.
Java provides three types of visibility modifiers: public, private and protected. They provide
different levels of protection as described below.
Public Access: Any variable or method is visible to the entire class in which it is defined. But,
to make a member accessible outside with objects, we simply declare the variable or method as
public. A variable or method declared as public has the widest possible visibility and accessible
everywhere.
Friendly Access (Default): When no access modifier is specified, the member defaults to a
limited version of public accessibility known as "friendly" level of access. The difference between the
"public" access and the "friendly" access is that the public modifier makes fields visible in all classes,
regardless of their packages while the friendly access makes fields visible only in the same package,
but not in other packages.
Protected Access: The visibility level of a "protected" field lies in between the public access
and friendly access. That is, the protected modifier makes the fields visible not only to all classes and
subclasses in the same package but also to subclasses in other packages
Private Access: private fields have the highest degree of protection. They are accessible only
with their own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. In the case of overriding public methods cannot be redefined as private type.
Private protected Access: A field can be declared with two
keywords private and protected together. This gives a visibility level in between the "protected"
access and "private" access. This modifier makes the fields visible in all subclasses regardless of what
package they are in. Remember, these fields are not accessible by other classes in the same package.
The following table summarizes the visibility provided by various access modifiers.
Access modifier public protected friendly private protected private

Own class Y Y Y Y Y
Sub class
Y Y Y Y N
in same package
Other classes
Y N Y N N
In same package
Sub class
Y N N N N
in other package
Other classes
Y N N N N
In other package

INTERFACES
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface method is
provided by the "implement" class:
Notes on Interfaces:
 Like abstract classes, interfaces cannot be used to create objects (in the example above, it is
not possible to create an "Animal" object in the MyMainClass)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces. Note: To implement multiple interfaces, separate them with a comma
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

Output
Some text…
Some other text…

STRING ARRAY
An Array is an essential and most used data structure in Java
. It is one of the most used data structure by programmers due to its efficient and productive nature;
The Array is a collection of similar data type elements. It uses a contiguous memory location to store
the elements.
A String Array is an Array of a fixed number of String values. A String is a sequence of
characters. Generally, a string is an immutable object, which means the value of the string can not be
changed. The String Array works similarly to other data types of Array.
In array, only a fixed set of elements can be stored. It is an index-based data structure, which starts
from the 0th position. The first element will take place in Index 0, and the 2nd element will take place
in Index 1, and so on.

String array,
o It is an object of the Array.
o It can be declared by the two methods; by specifying the size or without specifying the size.
o It can be initialized either at the time of declaration or by populating the values after the
declaration.
o The elements can be added to a String Array after declaring it.
o The String Array can be iterated using the for loop.
o The searching and sorting operation can be performed on the String Array.
Syntax
String[] stringArray1 //Declaration of the String Array without specifying the size
String[] stringArray2 = new String[2]; //Declarartion by specifying the size
Example
import java.util.Arrays;
public class StringArrayDemo {
public static void main(String[] args) {
String[] sa = new String[7]; // Creating a new Array of Size 7
sa[0] = "A"; // Adding Array elements
sa[1] = "B";
sa[2] = "C";
sa[3] = "D";
sa[4] = "E";
System.out.println("Original Array Elements:" + Arrays.toString(sa));
int numberOfItems = 5;
String newItem = "F"; // Expanding Array Elements Later
String newItem2 ="G";
sa[numberOfItems++] = newItem;
sa[numberOfItems++] = newItem2;
System.out.println("Array after adding two elements:" +
Arrays.toString(sa));
}
}
Output:
Original Array Elements:[A, B, C, D, E, null, null]
Array after adding two elements:[A, B, C, D, E, F, G]

String Methods
The String class has a set of built-in methods that you can use on strings.
Method Description Return Type

charAt() Returns the character at the specified index char


(position)

codePointAt() Returns the Unicode of the character at the int


specified index

codePointBefore() Returns the Unicode of the character before the int


specified index

codePointCount() Returns the Unicode in the specified text range of int


this String

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, ignoring int


case differences

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of boolean


characters

contentEquals() Checks whether a string contains the exact same boolean


sequence of characters of the specified
CharSequence or StringBuffer

copyValueOf() Returns a String that represents the characters of String


the character array

endsWith() Checks whether a string ends with the specified boolean


character(s)

equals() Compares two strings. Returns true if the strings boolean


are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the specified String


locale, format string, and arguments

getBytes() Encodes this String into a sequence of bytes using byte[]


the named charset, storing the result into a new
byte array

getChars() Copies characters from a string to an array of void


chars

hashCode() Returns the hash code of a string int

indexOf() Returns the position of the first found occurrence int


of specified characters in a string

intern() Returns the canonical representation for the string String


object

isEmpty() Checks whether a string is empty or not boolean

lastIndexOf() Returns the position of the last found occurrence int


of specified characters in a string

length() Returns the length of a specified string int

matches() Searches a string for a match against a regular boolean


expression, and returns the matches

offsetByCodePoints() Returns the index within this String that is offset int
from the given index by codePointOffset code
points

regionMatches() Tests if two string regions are equal boolean

replace() Searches a string for a specified value, and returns String


a new string where the specified values are
replaced

replaceFirst() Replaces the first occurrence of a substring that String


matches the given regular expression with the
given replacement

replaceAll() Replaces each substring of this string that String


matches the given regular expression with the
given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified boolean


characters

subSequence() Returns a new character sequence that is a CharSequenc


subsequence of this sequence e

substring() Returns a new string which is the substring of a String


specified string

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

valueOf() Returns the string representation of the specified String


value

StringBuffer class in Java


StringBuffer class is used to create a mutable string object. It means, it can be changed after it
is created. It represents growable and writable character sequence.
It is similar to String class in Java both are used to create string, but stringbuffer object can be
changed.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors.
1. StringBuffer(): It creates an empty string buffer and reserves space for 16 characters.
2. StringBuffer(int size): It creates an empty string and takes an integer argument to set capacity
of the buffer.
3. StringBuffer(String str): It creates a stringbuffer object from the specified string.
4. StringBuffer(charSequence []ch): It creates a stringbuffer object from the charsequence array.
Example: Creating a StringBuffer Object
In this example, we are creating string buffer object using StrigBuffer class and also testing its
mutability
public class Demo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("study");
System.out.println(sb);
// modifying object
sb.append("tonight");
System.out.println(sb); // Output: studytonight
}
}
Output
Study
Studytonight

Example: difference between String and StringBuffer


In this example, we are creating objects of String and StringBuffer class and modifying them,
but only stringbuffer object get modified.
class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study
StringBuffer strB = new StringBuffer("study");
strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
Output
Study
Studytonight
Important methods of StringBuffer class
The following methods are some most commonly used methods of StringBuffer class.
append()
This method will concatenate the string representation of any type of data to the end of the
StringBuffer object. append() method has several overloaded forms.
Example
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
}
}

Output
Test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
Example
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("test");
str.insert(2, 123);
System.out.println(str);
}
}
Output
Test123
Here the first parameter gives the index at which position the string will be inserted and string
representation of second parameter is inserted into StringBuffer object.

reverse()
This method reverses the characters within a StringBuffer object.
Example
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
}
}
Output
olleH

replace()
This method replaces the string from specified start index to the end index.

Example
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
}
}
Output
Hello java
UNIT – IV: Packages: Java API Packages – System Packages – Naming Conventions –Creating &
Accessing a Package – Adding Class to a Package – Hiding Classes. Exception Handling: Limitations
of Error handling – Advantages of Exception Handling - Types of Errors – Basics of Exception
Handling – try blocks – throwing an exception – catching an exception – finally statement.
Multithreading: Creating Threads – Life of a Thread – Defining & Running Thread – Thread Methods
– Thread Priority – Synchronization –Implementing Runnable interface – Thread Scheduling.

JAVA PACKAGES & API


A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages are
divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)

1.Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment. The library contains components for managing input, database
programming, and much more. The library is divided into packages and classes. Meaning you can
either import a single class (along with its methods and attributes), or a whole package that contain all
the classes that belong to the specified package.

Java API packages or built-in packages


Java provides a large number of classes grouped into different packages based on a particular
functionality.
Examples
java.lang: It contains classes for primitive types, strings, math functions, threads, and exceptions.
java.util: It contains classes such as vectors, hash tables, dates, Calendars, etc.
java.io: It has stream classes for Input/Output.
java.awt: Classes for implementing Graphical User Interface – windows, buttons, menus, etc.
java.net: Classes for networking
java. Applet: Classes for creating and implementing applets

To use a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class;
import package.name.*;

import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input,
write the following code:
Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used to
read a complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}

Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class from
the java.util package. This package also contains date and time facilities, random-number generator
and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example will
import ALL the classes in the java.util package:
Example
import java.util.*;

2.User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store
them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyPackageClass.java, and compile it:
C:\Users\...>javac MyPackageClass.java
Then compile the package:
C:\Users\...>javac -d . MyPackageClass.java
This forces the compiler to create the "mypack" package.
The -d keyword specifies the destination for where to save the class file. You can use any directory
name, like c:/user (windows), or, if you want to keep the package within the same directory, you can
use the dot sign ".", like in the example above.
When we compiled the package in the example above, a new folder was created, called "mypack".
To run the MyPackageClass.java file, write the following:
C:\Users\...>java mypack.MyPackageClass
The output will be:
This is my package!
APPLICATION PROGRAMMING INTERFACE (API)
An application programming interface (API), in the context of Java, is a collection of
prewritten packages, classes, and interfaces with their respective methods, fields and constructors.
Similar to a user interface, which facilitates interaction between humans and computers, an API
serves as a software program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API’s classes and packages, which are
helpful in minimizing the number of lines written within pieces of code.
Java Development Kit (JDK) is comprised of three basic components, as follows:
 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)
The Java API, included with the JDK, describes the function of each of its components. In Java
programming, many of these components are pre-created and commonly used. Thus, the programmer
is able to apply prewritten code via the Java API. After referring to the available API classes and
packages, the programmer easily invokes the necessary code classes and packages for
implementation.
The API is a library of available Java classes, packages and interfaces. The three API types are as
follows:
 Official Java core API, which is bundled with the JDK download
 Optional official Java APIs, which may be downloaded if needed
 Unofficial APIs, which are third-party APIs that may be downloaded from source websites
The APIs help programmers determine class or package functions, parameters and other necessary
information. The official API includes packages, e.g., applet packages, graphics and GUI swing
packages, input/output (IO) packages and Abstract Windows Toolkit (AWT), among others.

There are three frames when an API starts, as follows:


 The first frame shows all API components (classes and packages).
 When a particular package is selected, the second frame shows all interfaces, classes and
exceptions of that particular package.
 The third and primary frame provides an overview of all of API packages, which can be
expanded in the main frame to show the index, class hierarchy and help sections.
PACKAGE NAMING CONVENTIONS
Packages names follow the reverse order of domain names. For example, in a university, the
recommended convention is university.engineering.mech or university.tech.it or
university.arts.history etc.
In the following package:
java.util.Vector
 java is a top-level package
 util is a sub package
 and Vector is a class which is present in the subpackage util.

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java
can be categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the detailed
learning of creating and using user-defined packages.
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.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
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.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
Example of package that import the packagename.*
//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

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//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

EXCEPTION HANDLING
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and
unchecked exceptions.
What is Exception in Java?
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of
the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we
perform exception handling, the rest of the statements will be executed. That is why we use exception
handling in Java
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table describes each.
Keyword Description
try The "try" keyword is used to specify a block
where we should place an exception code. It
means we can't use try block alone. The try
block must be followed by either catch or
finally.
catch The "catch" block is used to handle the
exception. It must be preceded by try block
which means we can't use catch block alone. It
can be followed by finally block later.
finally The "finally" block is used to execute the
necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an
exception.
throws The "throws" keyword is used to declare
exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an
exception. It is always used with method
signature

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
In Java, Exception Handling in java is a very powerful technique by which runtime errors are
handled. Due to which the normal flow of the program remains. In other words, “Exception Handling
in Java is an important feature by which we can handle runtime errors caused by exceptions.”
An Exception Handling in java is an event that stops the normal flow of the program. Whenever there
is an exception in the program, the execution of the program ends and we get an error message
generated by the system. The good thing is that we can handle these exceptions.
“When a problem occurs during program execution, it is called an exception.” Exception occurs at
runtime.
There are two types of errors in Java.
1. Compile-Time Error
2. Run-Time Error
Compile-Time Error: This is a common error that comes by the compiler. When curly brace, semi-
colon or comma is not given in any syntax in the program, then this error occurs at compile-time.
Run-Time Error: Here the program is successfully run. But some such internal errors come, which
are given by the interpreter. This also closes the program.
If you see about the exception, when the program is successfully run at compile-time, then some
statements in the program are such that they are not executed by the compiler, at the same time it
creates an object related to those statements by the interpreter, when the object is created, then it is
thrown by the interpreter at run-time.
From this it is understood that, whenever such a condition comes in the program, then Exception
Handling is used in the program.
Difference between Exception and Error: –
Exception: Exception occurs at run-time, when Program; I get an exception divided by zero.
Error: Syntax error, format error or program in the program; goes out of memory, then error comes.
these errors; is critical. It is very difficult to find these errors. This error comes at compile-time.
Check Example for Normal Exception
Source Code:
class Sample
{
public static void main(String args[])
{
int p = 14/0;
}
}
Output :
C:\Program Files\Java\jdk1.5.0\bin>javac Sample.java
C:\Program Files\Java\jdk1.5.0\bin>java Sample
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Sample.main(Sample.java:5)
Advantage of Exception Handling in Java: –
1. Exception handling ensures that the flow of the program is maintained when an exception
occurs.
2. By this we can identify the types of errors.
3. By this we can write the error-handling code separately from the normal code.
Exception handling in Java Methods –
Following are some important methods present in Throwable class:-
 getMessage() – It returns the full detail message about the exception that has occurred. This
message is initialized in the Throwable constructor.
 getCause() – It returns the cause of the exception.
 toString() – It returns the class name to concatenate (add) the result of getMessage().
 printStackTrace() – It prints the result of toString() along with the stack trace.
User-defined Exceptions: –
We can create our own exception in Java. To create your own exception class, the following things
should be kept in mind.
 All exceptions that are there must be children of Throwable.
 If you want to write checked exception then you have to extend Exception class.
 If you want to write runtime exception then you will need to extend RuntimeException class.
syntax:-
class MyException extends Exception
{
}
How to do Exception Handling?
Exception in Java is handled by 5 keywords.
1. Try
2. Catch
3. Finally
4. Throw
5. Throws
Try –
 The “try” keyword is used to specify a block where we keep the exception code.
 There must be a catch block or finally block at the end of this block. This means that we
cannot use the try block alone.
 If it contains both catch and finally then their sequence should be try-catch-finally. Because if
their order is wrong then compile-time error will come.
 The code inside the try block should always be inside curly braces. Otherwise a compile-time
error will occur.
Its syntax –
try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{
}
Catch: –
 The “catch” block is used to handle the exception.
 It should always be used after the try block. This means that we cannot use catch alone.
 This block takes an argument. This argument must be either of type Throwable or of its sub-
class.
 Code inside the catch block should always be inside curly braces. Otherwise a compile-time
error will occur.
Its syntax –
try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}
Finally –
 The “finally” block is used to execute the important code of the program. Such as – closing
the database connection, closing the file resources etc.
 It is always used with try-catch block.
 There can be 2 combinations with finally. One try-finally and the other try-catch-finally.
 The finally block is always executed, whether the exception is handled or not.
 It executes after try and catch block.
Its syntax –
try
{
// code
}
catch(Exception_type1)
{
// catch block1
}
Catch(Exception_type2)
{
//catch block 2
}
finally
{
//finally block
// always execute
}
Throw –
 It is used to throw an exception.
 It is used with the exception of both checked and unchecked.
 Generally, the throw keyword is used to throw a user-defined exception.
Its Syntax:-
throw new Throwable_subclass;
Throws –
 The throws keyword is used to declare an exception.
 It does not throw exceptions.
 It is generally used to handle checked exceptions.
 If you do not want to handle the program with try and catch blocks, then you can handle it
with throws.
 It is always used with method signature.
Its Syntax:-
return_type method_name() throws exception_class_name
{
//method code
}
Example of Exception Handling in java –
public class Main
{
public static void main(String[ ] args)
{
try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println(“Something went wrong.”);
}
}
}
Its output:- Something went wrong.

MULTITHREADING
Java is a multi-threaded programming language which means we can develop multi-threaded
program using Java. A multi-threaded program contains two or more parts that can run concurrently
and each part can handle a different task at the same time making optimal use of the available
resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources such as a
CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide
specific operations within a single application into individual threads. Each of the threads can run in
parallel. The OS divides processing time not only among different applications, but also among each
thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in
the same program.
Creating thread
Create a Thread by Implementing a Runnable Interface
If your class is intended to be executed as a thread then you can achieve this by implementing
a Runnable interface. You will need to follow three basic steps −
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This method
provides an entry point for the thread and you will put your complete business logic inside this
method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is
the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to
run( ) method. Following is a simple syntax of start() method −
void start();
Example
Here is an example that creates a new thread and starts running it −

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

This will produce the following result −


Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that extends Thread class using the
following two simple steps. This approach provides more flexibility in handling multiple threads
created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method provides an entry
point for the thread and you will put your complete business logic inside this method. Following is a
simple syntax of run() method −
public void run( )
Step 2
Once Thread object is created, you can start it by calling start() method, which executes a call to run(
) method. Following is a simple syntax of start() method −
void start( );
Example
Here is the preceding program rewritten to extend the Thread −

class ThreadDemo extends Thread {


private Thread t;
private String threadName;

ThreadDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");


T2.start();
}
}

This will produce the following result −


Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

LIFE CYCLE OF A THREAD


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. The following diagram shows the complete life cycle of a thread.
Following are the stages of the life cycle −
 New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it completes its task
or otherwise terminates.

THREAD METHODS
Following is the list of important methods available in the Thread class.
S.No. Method & Description

1 public void start()


Starts the thread in a separate path of execution, then invokes the run() method on this
Thread object.

2 public void run()


If this Thread object was instantiated using a separate Runnable target, the run() method is
invoked on that Runnable object.

3 public final void setName(String name)


Changes the name of the Thread object. There is also a getName() method for retrieving
the name.

4 public final void setPriority(int priority)


Sets the priority of this Thread object. The possible values are between 1 and 10.

5 public final void setDaemon(boolean on)


A parameter of true denotes this Thread as a daemon thread.

6 public final void join(long millisec)


The current thread invokes this method on a second thread, causing the current thread to
block until the second thread terminates or the specified number of milliseconds passes.

7 public void interrupt()


Interrupts this thread, causing it to continue execution if it was blocked for any reason.

8 public final boolean isAlive()


Returns true if the thread is alive, which is any time after the thread has been started but
before it runs to completion.
The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the currently
running thread.
S.No. Method & Description

1 public static void yield()


Causes the currently running thread to yield to any other threads of the same priority that are
waiting to be scheduled.

2 public static void sleep(long millisec)


Causes the currently running thread to block for at least the specified number of milliseconds.

3 public static boolean holdsLock(Object x)


Returns true if the current thread holds the lock on the given Object.

4 public static Thread currentThread()


Returns a reference to the currently running thread, which is the thread that invokes this method.

5 public static void dumpStack()


Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.
Example
The following ThreadClassDemo program demonstrates some of these methods of the Thread class.
Consider a class DisplayMessage which implements Runnable −
public class DisplayMessage implements Runnable {
private String message;

public DisplayMessage(String message) {


this.message = message;
}

public void run() {


while(true) {
System.out.println(message);
}
}
}
THREAD PRIORITIES
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and are very much platform dependent.

THREAD SCHEDULING

Features :
1. The JVM schedules using a preemptive , priority � based scheduling algorithm.
2. All Java threads have a priority and the thread with he highest priority is scheduled to run by
the JVM.
3. In case two threads have the same priority a FIFO ordering is followed.

A different thread is invoked to run in case one of the following events occur:
1.The currently running thread exits the Runnable state ie either blocks or terminates.
2. A thread with a higher priority than the thread currently running enters the Runnable state.
The lower priority thread is preempted and the higher priority thread is scheduled to run.

Time Slicing is dependent on the implementation. A thread can voluntarily yield control through the
yield() method. Whenever a thread yeilds control of the CPU another thread of the same priority is
scheduled to run. A thread voluntarily yielding control of the CPU is called Cooperative Multitasking.

SYNCHRONIZATION
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. In the Multithreading concept, multiple threads try to access the shared resources at a
time to produce inconsistent results. The synchronization is necessary for reliable communication
between threads. Types of Synchronization
Synchronization is classified into two types
 Process Synchronization
 Thread Synchronization
Process Synchronization:
 The process is nothing but a program under execution. It runs independently isolated
from another process. The resources like memory and CPU time, etc. are allocated to
the process by the operation System.
Thread Synchronization:
Thread synchronization is two types, they are:
1.Mutual Exclusive:
A Mutex or Mutual Exclusive helps only one thread to access the shared resources. It won’t allow
the accessing of shared resources at a time. It can be achieved in the following ways.
 Synchronized Method
 Synchronized block
 Static Synchronization
2. Cooperation (Inter Thread Communication in java)
Java Synchronized Method
If we use the Synchronized keywords in any method then that method is Synchronized Method.
 It is used to lock an object for any shared resources.
 The object gets the lock when the synchronized method is called.
 The lock won’t be released until the thread completes its function.
Syntax:
Acess_modifiers synchronized return_type method_name (Method_Parameters) {
// Code of the Method.
}
Java Synchronized Method Example:
class Power{
synchronized void printPower(int n){//method synchronized
int temp = 1;
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName() + ":- " +n + "^"+ i + " value: " +
n*temp);
temp = n*temp;
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
}
}
}
class Thread1 extends Thread{
Power p;
Thread1(Power p){
this.p=p;
}
public void run(){
p.printPower(5);
}
}
class Thread2 extends Thread{
Power p;
Thread2(Power p){
this.p=p;
}
public void run(){
p.printPower(8);
}
}
public class Synchronization_Example2{
public static void main(String args[]){
Power obj = new Power();//only one object
Thread1 p1=new Thread1(obj);
Thread2 p2=new Thread2(obj);
p1.start();
p2.start();
}
}
Output:
Thread-0:- 5^1 value: 5
Thread-0:- 5^2 value: 25
Thread-0:- 5^3 value: 125
Thread-0:- 5^4 value: 625
Thread-0:- 5^5 value: 3125
Thread-1:- 8^1 value: 8
Thread-1: – 8^2 value: 64
Thread-1:- 8^3 value: 512
Thread-1:- 8^4 value: 4096
Thread-1:- 8^5 value: 32768
Here we used synchronized keywords. It helps to execute a single thread at a time. It is not
allowing another thread to execute until the first one is completed, after completion of the first
thread it allowed the second thread. Now we can see the output correctly the powers 5 and 8 from
n1 to n5. Thread-0 completed then only thread-1 begin.
UNIT – V:- I/O Streams: File – Streams – Advantages - The stream classes – Byte streams –
Character streams. Applets: Introduction – Applet Life cycle – Creating & Executing an Applet –
Applet tags in HTML – Parameter tag – Aligning the display - Graphics Class: Drawing and filling
lines – Rectangles – Polygon – Circles – Arcs – Line Graphs – Drawing Bar charts AWT Components
and Even Handlers: Abstract window tool kit – Event Handlers – Event Listeners – AWT Controls
and Event Handling: Labels – Text Component – Action Event – Buttons – Check Boxes – Item
Event – Choice– Scrollbars – Layout Managers- Input Events – Menus.

I/O STREAMS
I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Input Stream: These streams are used to read data that must be taken as an input from a source array
or file or any peripheral device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc. Java application uses an input stream to read data from a source; it may
be a file, an array, peripheral device or socket.
Output Stream: These streams are used to write data as outputs into an array or file or any output
peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.

STREAM
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it
is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
This is the standard output stream that is used to produce the result of a program on an
output device like the computer screen.
2) System.in: standard input stream
This is the standard input stream that is used to read characters from the keyboard or any
other standard input device.
3) System.err: standard error stream
This is the standard error stream that is used to output all the error data that a program
might throw, on a computer screen or any standard output device.
All these stream uses 3 functions:
print()
println()
printf()
ByteStream
This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used
to read from the source and FileOutputStream is used to write to the destination. Here is the list of
various ByteStream Classes:
ByteStream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStream This is used for Buffered Output Stream.

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.

EXAMPLE
// Byte Stream to copy contents of one file to another file.
import java.io.*;
public class BStream
{
public static void main(
String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
try
{
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");
// Reading source file and writing
// content to target file byte by byte
int temp;
while ((temp = sourceStream.read())!= -1)
targetStream.write((byte)temp);
}
finally
{
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}
OUTPUT
Shows contents of file test.txt

CharacterStream
In Java, characters are stored using Unicode conventions (Refer this for details). Character
stream automatically allows us to read/write data character by character. Though it has many
classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are
character streams used to read from the source and write to the destination respectively. Here is the
list of various CharacterStream Classes:

CharacterStream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReader This output stream is used to translate character to byte.

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.

EXAMPLE
import java.io.*;
public class GfG
{
public static void main(String[] args) throws IOException
{
FileReader s = null;
try
{
s= new FileReader("test.txt");
int temp;
while ((temp = s.read())!= -1)
System.out.println((char)temp);
}
Finally
{
if (s!= null)
s.close();
}
}
}
ADVANTAGES
The streaming interface to I/O in Java provides a clean abstraction for a complex and often
cumbersome task. The composition of the filtered stream classes allows you to dynamically build the
custom streaming interface to suit your data transfer requirements. Java programs written to adhere to
the abstract, high-level InputStream, OutputStream, Reader, and Writer classes will function
properly in the future even when new and improved concrete stream classes are invented. As you will
see in Chapter 22, this model works very well when we switch from a file system–based set of
streams to the network and socket streams. Finally, serialization of objects plays an important role in
many types of Java programs. Java’s serialization I/O classes provide a portable solution to this
sometimes tricky task.
Streams are a more declarative style or a more expressive style. It may be considered better to
declare your intent in code, than to describe how it's done
Streams have a strong affinity with functions. Java 8 introduces lambdas and functional interfaces,
which opens a whole toybox of powerful techniques. Streams provide the most convenient and natural
way to apply functions to sequences of objects.
Streams encourage less mutability. This is sort of related to the functional programming aspect --
the kind of programs you write using streams tend to be the kind of programs where you don't modify
objects.
Streams encourage looser coupling. Your stream-handling code doesn't need to know the source of
the stream, or its eventual terminating method.
Streams provide scope for future efficiency gains. Some people have benchmarked and found that
single-threaded streams from in-memory Lists or arrays can be slower than the equivalent loop. This
is plausible because there are more objects and overheads in play.

APPLETS
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including
the following −
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or
a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
APPLET LIFE CYCLE
An applet is a special type of program embedded in the web page to generate dynamic content.
Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().
These methods are invoked by the browser to execute. Along with the browser, the applet also
works on the client side, thus having less processing time.
Methods of Applet Life Cycle

There are five methods in the Applet class


 init −The init() method is the first method to execute when the applet is executed. Variable
declaration and initialization operations are performed in this method.
SYNTAX:
public void init();
the above statement is used to initialized the Applet. It is invoked only once.

 start − The start() method contains the actual code of the applet that should run. The start()
method executes immediately after the init() method. It also executes whenever the applet is
restored, maximized or moving from one tab to another tab in the browser.
SYNTAX:
public void start();
the above statement is invoked after the init() method or browser is maximized. It is used to
start the Applet.
 stop − The stop() method stops the execution of the applet. The stop() method executes when
the applet is minimized or when moving from one tab to another in the browser.
SYNTAX:
public void stop();
the above statement is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.

 destroy − The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed. stop() method executes just before when destroy() method
is invoked. The destroy() method removes the applet object from memory.
SYNTAX:
public void destroy();
the above statement is used to destroy the Applet. It is invoked only once.

 paint − The paint() method is used to redraw the output on the applet display area. The
paint() method executes after the execution of start() method and whenever the applet or
browser is resized.
SYNTAX:
public void paint(Graphics g):

EXAMPLE
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
public void init()
{
System.out.println("Applet initialized");
}
public void start()
{
System.out.println("Applet execution started");
}
public void stop()
{
System.out.println("Applet execution stopped");
}
public void paint(Graphics g)
{
System.out.println("Painting...");
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
A simple applet program
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required
but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

CREATING AND EXECUTING AN APPLET


An applet is a Java program that runs in a Java-compatible browser such as Internetexplorer.
This feature allows users to display graphics and to run programs over the Internet. An applet allows
web documents to be both animated and interactive.

Step 1: Import applet package and awt package:


To create an applet, our program must import the Applet class. This class is found in
the java.applet package. The Applet class contains code that works with a browser to create a display
area. We also need to import the java.awt package. "awt” stands for “Abstract Window Toolkit”. The
java.awt package includes classes like Graphics.

Step 2: Extend the Applet class:


Then, a class must be defined that inherits from the class ‘Applet’. It contains the methods to
paint the screen. The inherited class must be declared public.

Step 3: Override the paint method to draw text or graphics:


The paint method needs the Graphics object as its parameter.
Syntax: public void paint(Graphics g) { … }
The Graphics class object holds information about painting. We can invoke methods like
drawLine(), drawCircle() and etc using this object.

Example
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to Apoorva”,50,50);
}
}

Step 4: Compiling the Program:


After writing the program, we compile it using the command "javac MyApplet.java". This
command will compile our code so that we now have MyApplet.class file.

Step 5: Adding applet to HTML document:


To run the applet we need to create the HTML document. The BODY section of the HTML
document allows APPLET tag. The HTML file looks something like this:
<HTML>
<BODY>
<APPLET codebase="MyAppPath" code="MyApp.class" width=200 height=200>
</APPLET>
</BODY>
</HTML>

Step 6: Running an applet:


The applet can be run in two ways
1. Using appletviewer: To run the appletviewer, type appletviewer filename.html
2. Using web browser: Open the web browser, type in the full address of html file.

APPLET TAGS IN HTML


HTML <applet> tag was used to embed the Java applet in an HTML document. This element
has been deprecated in HTML 4.0 and instead of it we can use <object> and newly added element
<embed>.
The use of Java applet is also deprecated, and most browsers do not support the use of plugins.
Syntax
<applet code="URL" height="200" width="100">.............</applet>
Example
<html>
<head>
<title>Applet Tag</title></head>
<body>
<p>Example of Applet Tag</p>
<applet code="Shapes.class" align="right" height="200" width="300">
<b>Sorry! you need Java to see this</b>
</applet>
</body>
</html>

OUTPUT
Sorry! you need Java to see this

Attribute Value Description


Parameter
name
tag
code URL It specifies the URL of Java applet class file. Para
meters
width pixels It specifies the display width of the applet panel. specify
height pixels It specifies the display height of applet panel extra
information
align o left It specifies the position of applet application that can be
o right relative to surrounding content. passed to
o top an applet
o middle from the
o bottom HTML
alt text It is used to display alternative text in case browser page.
Parameters
does not support Java.
are
archive URL This specifies the archived or compressed version specified
of an applet application. using the
HTML’s pa
object name It specifies the URL or reference to a serialized
ram tag.
representation of an applet.

codebase URL It specifies the exact or relative URL of applets Param tag
.class file specified in the code attribute. The
<param>
hspace pixels It specifies the horizontal space around the applet.
tag is a sub
vspace pixels It specifies the vertical space around the applet. tag of the
<applet>
name name It specifies the name for the applet tag. The
<param> tag contains two attributes: name and value which are used to specify the name of the
parameter and the value of the parameter respectively. For example, the param tags for passing name
and age parameters looks as shown below:
<param name=”name” value=”Ramesh” />
<param name=”age” value=”25″ />
now, these two parameters can be accessed in the applet program using the getParameter() method of
the Applet class.
getParameter() method
The getParameter() method of the Applet class can be used to retrieve the parameters passed
from the HTML page.
The syntax of getParameter() method is as follows:
String getParameter(String param-name)
Example
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Output

ALIGNING THE DISPLAY


The HTML applet align attribute is used to specify the alignment of the <applet> element
or the content present inside the applet element.
Syntax:
<applet align="left | right | center | justify";>

Attribute Values:
 left: It sets the content to the left-align.
 right: It sets the content to the right-align.
 center: I sets the content element to the center.
 justify: It sets the content to the justify position.

EXAMPLE
<html>
<head>
<title>
HTML | applet align Attribute
</title>
</head>
<body>
<applet code="HelloWorld" alt="sample" align="right" width=200 height=60>
</applet>
<h1>
HTML applet align attribute
</h1>
<h2>Hello Java</h2>
<p>
a computer science portal
</p>
</body>
</html>

OUTPUT:
HTML applet align attribute
Hello Java
a computer science portal

GRAPHICS CLASS

 The graphics class defines a number of drawing functions,


 Each shape can be drawn edge-only or filled. To draw shapes on the screen, we may
call one of the methods available in the graphics class.
 The most commonly used drawing methods included in the graphics class are listed
below. To draw a shape, we only need to use the appropriate method with the required
arguments.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
LINES AND RECTANGLES
Lines are drawn by means of the drawLine() method.
Syntax
void drawLine(int startX, int startY, int endX, int endY)
drawLine() displays a line in the current drawing color that begins at (start X, start Y) and ends
at (endX, end Y).
Example
import java.awt.*;
import java.applet.*;
/*
<applet code=”Lines” width=300, height =250>
</applet>
public class Lines extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);
g.drawLine(40,25,250,180);
g.drawLine(5,290,80,19);
}
}
Output

RECTANGLE
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectanlge" width=300 Height=300>
</applet>
*/
public class Rectangle extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,100,100,0);
g.drawRoundRect(190,10,60,50,15,15); g.fillRoundRect(70,90,140,100,30,40);
}
}
Output

CIRCLES AND ELLIPSES


import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 Height=300>
</applet>
*/
public class Ellipses extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10,10,60,50);
g.fillOval(100,10,75,50);
g.drawOval(190,10,90,30);
g.fillOval(70,90,140,100);
}
}
Output
Drawing Arcs
import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 Height=300>
</applet>
*/
public class Arcs extends Applet
{
public void paint(Graphics g)
{
g.drawArc(10,40,70,70,0,75);
g.fillArc(100,40,70,70,0,75);
g.drawArc(10,100,70,80,0,175);
g.fillArc(100,100,70,90,0,270);
g.drawArc(200,80,80,80,0,180);
}
}
Output

Drawing Polygons
import java.awt.*;
import java.applet.*;
/*
<applet code="Polygon" width=300 Height=300>
</applet>
*/
public class Polygon extends Applet
{
public void paint(Graphics g)
{
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);
}
}
Output

Line Graph
import java.awt.*;
import java.applet.*;
public class Line_Graph extends Applet
{
int x[]={ 0, 60, 120, 180, 240, 300, 360, 400};
int y[]={ 400, 280, 220, 140, 60, 60, 100, 220};
int z=x.length;
public void paint(Graphics g)
{
g.drawPolygon(x, y, z);
}
}

<html>
<head>
<body>
<applet code=” Line_Graph.class” width=”640” height=”480” ></applet>
</body>
</html>

Output
Draw bar chart
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class BarChart extends JApplet
{
public void init()
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
String v = getParameter("values");
if (v == null) return;
int n = Integer.parseInt(v);
double[] values = new double[n];
String[] names = new String[n];
for (int i = 0; i < n; i++)
{
values[i] = Double.parseDouble(getParameter("value." + (i + 1)));
names[i] = getParameter("name." + (i + 1));
}
add(new Component(values, names, getParameter("title")));
}
});
}
}
class Component extends JComponent
{
public Component(double[] v, String[] n, String t)
{
values = v;
names = n;
title = t;
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
if (values == null) return;
double minValue = 0;
double maxValue = 0;
for (double v : values)
{
if (minValue > v) minValue = v;
if (maxValue < v) maxValue = v;
}
if (maxValue == minValue) return;
int panelWidth = getWidth();
int panelHeight = getHeight();
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
double titleWidth = titleBounds.getWidth();
double top = titleBounds.getHeight();
double y = -titleBounds.getY();
double x = (panelWidth - titleWidth) / 2;
g2.setFont(titleFont);
g2.drawString(title, (float) x, (float) y);
LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
double bottom = labelMetrics.getHeight();
y = panelHeight - labelMetrics.getDescent();
g2.setFont(labelFont);
double scale = (panelHeight - top - bottom) / (maxValue - minValue);
int barWidth = panelWidth / values.length;
for (int i = 0; i < values.length; i++)
{
double x1 = i * barWidth + 1;
double y1 = top;
double height = values[i] * scale;
if (values[i] >= 0) y1 += (maxValue - values[i]) * scale;
else
{
y1 += maxValue * scale;
height = -height;
}
Rectangle2D rect = new Rectangle2D.Double(x1, y1, barWidth - 2, height);
g2.setPaint(Color.BLUE);
g2.fill(rect);
g2.setPaint(Color.BLACK);
g2.draw(rect);
Rectangle2D labelBounds = labelFont.getStringBounds(names[i], context);
double labelWidth = labelBounds.getWidth();
x = x1 + (barWidth - labelWidth) / 2;
g2.drawString(names[i], (float) x, (float) y);
}
}
private double[] values;
private String[] names;
private String title;
}

<applet code="BarChart.class" width=640 height=520>


<param name="title" value="Annual Turnover (Crores) of a Company during 2012 to 2020"/>
<param name="values" value="9"/>
<param name="name.1" value="2012"/>
<param name="name.2" value="2013"/>
<param name="name.3" value="2014"/>
<param name="name.4" value="2015"/>
<param name="name.5" value="2016"/>
<param name="name.6" value="2017"/>
<param name="name.7" value="2018"/>
<param name="name.8" value="2019"/>
<param name="name.9" value="2020"/>
<param name="value.1" value="4000"/>
<param name="value.2" value="5500"/>
<param name="value.3" value="8000"/>
<param name="value.4" value="25000"/>
<param name="value.5" value="40000"/>
<param name="value.6" value="50000"/>
<param name="value.7" value="35000"/>
<param name="value.8" value="20500"/>
<param name="value.9" value="1500"/>
</applet>
Output
AWT COMPONENTS AND EVENT HANDLERS
Abstract window tool kit
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavy weight i.e. its components are using the resources of underlying
operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List, etc

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels, etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel. It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
1.Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window. We need to create an instance of Window class to create this
container.
2.Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc. An
instance of Panel class creates a container, in which we can add components.
3.Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used container
while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this
component.

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

public void Defines the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean Changes the visibility of the


status) component, by default false.

Example
import java.awt.*;
class AWTExample
{
AWTExample()
{
Frame f = new Frame();
Label l = new Label("Employee id:");
Button b = new Button("Submit");
TextField t = new TextField();
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b);
f.add(l);
f.add(t);
f.setSize(400,300);
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
AWTExample obj = new AWTExample();
}
}
Output
Event Handlers
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event
handling.
We perform event handling in Swing and AWT and we can also do it in Applets.
As we know, Graphical Programming Interfaces (GUIs) contain the components of the user interface.
The GUI components are responsible to generate events based on user interactions like clicking the
mouse or a key and so on. When an applet is designed, these events are captured and the appropriate
actions are performed in response to each of those events provided.
For handling events, we need event handlers, that must be available in Java. The procedure to be
followed when an event is generated is:
1. First, we must find the type of event that took place.
2. Now, find the component that generated the event.
3. Finally, we need the appropriate code that handles the event.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
EXAMPLE
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[])
{
new AEvent();
}
}

public void setBounds(int xaxis, int yaxis, int width, int height);
This code have been used in the above example that sets the position of the component it may
be button, textfield etc.

OUTPUT
EVENT LISTENER
The Event listener represent the interfaces responsible to handle events. Java provides us
various Event listener classes but we will discuss those which are more frequently used. Every
method of an event listener method has a single argument as an object which is subclass of
EventObject class. For example, mouse event listener methods will accept instance of MouseEvent,
where MouseEvent derives from EventObject.
EventListner interface
It is a marker interface which every listener interface has to extend.This class is defined in
java.util package.
Class declaration
Following is the declaration for java.util.EventListener interface:
public interface EventListener
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.

S. No. Control & Description

1 ActionListener
This interface is used for receiving the action events.

2 ComponentListener
This interface is used for receiving the component events.

3 ItemListener
This interface is used for receiving the item events.

4 KeyListener
This interface is used for receiving the key events.

5 MouseListener
This interface is used for receiving the mouse events.

6 TextListener
This interface is used for receiving the text events.

7 WindowListener
This interface is used for receiving the window events.
8 AdjustmentListener
This interface is used for receiving the adjusmtent events.

9 ContainerListener
This interface is used for receiving the container events.

10 MouseMotionListener
This interface is used for receiving the mouse motion events.

11 FocusListener
This interface is used for receiving the focus events.

AWT CONTROLS AND EVENT HANDLING


Label
The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a user cannot
edit it directly. It is called a passive control as it does not create any event when it is accessed. To
create a label, we need to create the object of Label class.
AWT Label Class Declaration

AWT Label Fields


The java.awt.Component class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Label class Constructors


Sr. Constructor Description
no.

1. Label() It constructs an empty label.

2. Label(String text) It constructs a label with the


given string (left justified by
default).

3. Label(String text, It constructs a label with the


int alignement) specified string and the
specified alignment.

Label Class Methods


Sr. Method name Description
no.

1. void setText(String text) It sets the texts for


label with the
specified text.
2. void setAlignment(int It sets the alignment
alignment) for label with the
specified alignment.

3. String getText() It gets the text of the


label

4. int getAlignment() It gets the current


alignment of the
label.

5. void addNotify() It creates the peer for


the label.

6. AccessibleContext It gets the Accessible


getAccessibleContext() Context associated
with the label.

7. protected String It returns the string


paramString() the state of the label.
Method inherited
The above methods are inherited by the following classes:
o java.awt.Component
o java.lang.Object
Java AWT Label Example
In the following example, we are creating two labels l1 and l2 using the Label(String text)
constructor and adding them into the frame.
LabelExample.java
import java.awt.*;
public class LabelExample {
public static void main(String args[]){
Frame f = new Frame ("Label example");
Label l1, l2;
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
f.add(l1);
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:
TEXT COMPONENT
The object of a TextField class is a text component that allows a user to enter a single line text
and edit it. It inherits TextComponent class, which further inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed), the event is sent
to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also be done
using ActionEvent; if the ActionEvent is enabled on the text field, then the ActionEvent may be fired
by pressing return key. The event is handled by the ActionListener interface.
AWT TextField Class Declaration

Syntax: public class TextField extends TextComponent


TextField Class constructors
Sr. Constructor Description
no.

1. TextField() It constructs a new text field component.

2. TextField(String It constructs a new text field initialized with the


text) given string text to be displayed.

3. TextField(int It constructs a new textfield (empty) with given


columns) number of columns.

4. TextField(String It constructs a new text field with the given text


text, int columns) and given number of columns (width).

TextField Class Methods


Sr. Method name Description
no.

1. void addNotify() It creates the peer of text field.

2. boolean echoCharIsSet() It tells whether text field has


character set for echoing or not.

3. void It adds the specified action


addActionListener(ActionListener l) listener to receive action events
from the text field.

4. ActionListener[] getActionListeners() It returns array of all action


listeners registered on text
field.

5. AccessibleContext It fetches the accessible context


getAccessibleContext() related to the text field.

6. int getColumns() It fetches the number of


columns in text field.

7. char getEchoChar() It fetches the character that is


used for echoing.

8. Dimension getMinimumSize() It fetches the minimum


dimensions for the text field.

9. Dimension getMinimumSize(int It fetches the minimum


columns) dimensions for the text field
with specified number of
columns.

10. Dimension getPreferredSize() It fetches the preferred size of


the text field.

11. Dimension getPreferredSize(int It fetches the preferred size of


columns) the text field with specified
number of columns.

12. protected String paramString() It returns a string representing


state of the text field.

13. Protected void It processes action events


processActionEvent(ActionEvent e) occurring in the text field by
dispatching them to a registered
ActionListener object.

14. protected void It processes the event on text


processEvent(AWTEvent e) field.

15. void It removes specified action


removeActionListener(ActionListener listener so that it doesn't
l) receive action events anymore.

16. void setColumns(int columns) It sets the number of columns


in text field.

17. void setEchoChar(char c) It sets the echo character for


text field.

18. void setText(String t) It sets the text presented by this


text component to the specified
text.
Method Inherited
The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
Java AWT TextField Example

import java.awt.*;
public class TextFieldExample1 {
public static void main(String args[]) {
Frame f = new Frame("TextField Example");
TextField t1, t2;
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

ACTION EVENT
This class is defined in java.awt.event package. The ActionEvent is generated when button is
clicked or the item of a list is double clicked.
Class declaration
Following is the declaration for java.awt.event.ActionEvent class:
public class ActionEvent extends AWTEvent
Field
Following are the fields for java.awt.event.ActionEvent class:
 static int ACTION_FIRST -- The first number in the range of ids used for action events.
 static int ACTION_LAST -- The last number in the range of ids used for action events.
 static int ACTION_PERFORMED -- This event id indicates that a meaningful action
occured.
 static int ALT_MASK -- The alt modifier.
 static int CTRL_MASK -- The control modifier.
 static int META_MASK -- The meta modifier.
 static int SHIFT_MASK -- The shift modifier.
Class constructors
S.No. Constructor & Description

1 ActionEvent(java.lang.Object source, int id,


java.lang.String command)
Constructs an ActionEvent object.

2 ActionEvent(java.lang.Object source, int id,


java.lang.String command, int modifiers)
Constructs an ActionEvent object with modifier keys.

3 ActionEvent(java.lang.Object source, int id,


java.lang.String command, long when, int modifiers)
Constructs an ActionEvent object with the specified
modifier keys and timestamp.
Class methods
S.N. Method & Description

1 java.lang.String getActionCommand()
Returns the command string associated with this action.

2 int getModifiers()
Returns the modifier keys held down during this action
event.

3 long getWhen()
Returns the timestamp of when this event occurred.

4 java.lang.String paramString()
Returns a parameter string identifying this action event.
Methods inherited
This class inherits methods from the following classes:
 java.awt.AWTEvent
 java.util.EventObject
 java.lang.Object

BUTTONS
A button is basically a control component with a label that generates an event when pushed.
The Button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.
When we press a button and release it, AWT sends an instance of ActionEvent to that button
by calling processEvent on the button. The processEvent method of the button receives the all the
events, then it passes an action event by calling its own method processActionEvent. This method
passes the action event on to action listeners that are interested in the action events generated by the
button.
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's action
command as a messaging protocol.
AWT Button Class Declaration
Syntax: public class Button extends Component implements Accessible
Button Class Constructors
Following table shows the types of Button class constructors
Sr. Constructor Description
no.

1. Button( ) It constructs a new button with an empty string


i.e. it has no label.

2. Button (String It constructs a new button with given string as


text) its label.
Button Class Methods
Sr. Method Description
no.

1. void setText (String text) It sets the string message on


the button

2. String getText() It fetches the String message


on the button.

3. void setLabel (String label) It sets the label of button with


the specified string.

4. String getLabel() It fetches the label of the


button.

5. void addNotify() It creates the peer of the


button.

6. AccessibleContext It fetched the accessible


getAccessibleContext() context associated with the
button.

7. void It adds the specified action


addActionListener(ActionListener listener to get the action events
l) from the button.

8. String getActionCommand() It returns the command name


of the action event fired by the
button.

9. ActionListener[ ] It returns an array of all the


getActionListeners() action listeners registered on
the button.

10. T[ ] It returns an array of all the


getListeners(Class listenerType) objects currently registered as
FooListeners upon this Button.
11. protected String paramString() It returns the string which
represents the state of button.

12. protected void It process the action events on


processActionEvent (ActionEvent the button by dispatching them
e) to a registered ActionListener
object.

13. protected void processEvent It process the events on the


(AWTEvent e) button

14. void removeActionListener It removes the specified action


(ActionListener l) listener so that it no longer
receives action events from the
button.

15. void setActionCommand(String It sets the command name for


command) the action event given by the
button.
Java AWT Button Example
ButtonExample.java
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
Frame f = new Frame("Button Example");
Button b = new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

To compile the program using command prompt type the following commands
javac ButtonExample.java
If there's no error, we can execute the code using:
java ButtonExample

Output:
CHECK BOX
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
AWT Checkbox Class Declaration
Syntax: public class Checkbox extends Component implements ItemSelectable, Accessible
Checkbox Class Constructors
Sr. Constructor Description
no.

1. Checkbox() It constructs a checkbox with no string as


the label.

2. Checkbox(String It constructs a checkbox with the given


label) label.

3. Checkbox(String label, It constructs a checkbox with the given label


boolean state) and sets the given state.

4. Checkbox(String label, It constructs a checkbox with the given


boolean state, label, set the given state in the specified
CheckboxGroup checkbox group.
group)

5. Checkbox(String label, It constructs a checkbox with the given


CheckboxGroup label, in the given checkbox group and set to
group, boolean state) the specified state.
Method inherited by Checkbox
The methods of Checkbox class are inherited by following classes:
o java.awt.Component
o java.lang.Object
Checkbox Class Methods
Sr. Method name Description
no.

1. void addItemListener(ItemListener It adds the given item listener


IL) to get the item events from the
checkbox.

2. AccessibleContext It fetches the accessible context


getAccessibleContext() of checkbox.
3. void addNotify() It creates the peer of checkbox.

4. CheckboxGroup It determines the group of


getCheckboxGroup() checkbox.

5. ItemListener[] getItemListeners() It returns an array of the item


listeners registered on
checkbox.

6. String getLabel() It fetched the label of


checkbox.

7. T[] getListeners(Class listenerType) It returns an array of all the


objects registered as
FooListeners.

8. Object[] getSelectedObjects() It returns an array (size 1)


containing checkbox label and
returns null if checkbox is not
selected.

9. boolean getState() It returns true if the checkbox is


on, else returns off.

10. protected String paramString() It returns a string representing


the state of checkbox.

11. protected void It processes the event on


processEvent(AWTEvent e) checkbox.

12. protected void It process the item events


processItemEvent(ItemEvent e) occurring in the checkbox by
dispatching them to registered
ItemListener object.

13. void It removes the specified item


removeItemListener(ItemListener l) listener so that the item listener
doesn't receive item events
from the checkbox anymore.

14. void It sets the checkbox's group to


setCheckboxGroup(CheckboxGroup the given checkbox.
g)

15. void setLabel(String label) It sets the checkbox's label to


the string argument.

16. void setState(boolean state) It sets the state of checkbox to


the specified state.
Java AWT Checkbox Example
In the following example we are creating two checkboxes using the Checkbox(String label)
constructor and adding them into the Frame using add() method.
CheckboxExample.java
import java.awt.*;
public class CheckboxExample
{
CheckboxExample()
{
Frame f = new Frame("Checkbox Example");
Checkbox c1 = new Checkbox("C++");
c1.setBounds(100, 100, 50, 50);
Checkbox c2 = new Checkbox("Java", true);
c2.setBounds(100, 150, 50, 50);
f.add(c1);
f.add(c2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main (String args[])
{
new CheckboxExample();
}
}
Output:

CHOICE
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
Syntax: public class Choice extends Component implements ItemSelectable, Accessible
Choice Class constructor
Sr. Constructor Description
no.

1. Choice() It constructs a new choice


menu.
Methods inherited by class
The methods of Choice class are inherited by following classes:
o
java.awt.Component
o java.lang.Object
Choice Class Methods
Sr. Method name Description
no.

1. void add(String item) It adds an item to the choice


menu.

2. void It adds the item listener that


addItemListener(ItemListener l) receives item events from the
choice menu.

3. void addNotify() It creates the peer of choice.

4. AccessibleContext It gets the accessbile context


getAccessibleContext() related to the choice.

5. String getItem(int index) It gets the item (string) at the


given index position in the
choice menu.

6. int getItemCount() It returns the number of items of


the choice menu.

7. ItemListener[] It returns an array of all item


getItemListeners() listeners registered on choice.

8. T[] Returns an array of all the


getListeners(Class listenerType) objects currently registered as
FooListeners upon this Choice.

9. int getSelectedIndex() Returns the index of the


currently selected item.

10. String getSelectedItem() Gets a representation of the


current choice as a string.

11. Object[] getSelectedObjects() Returns an array (length 1)


containing the currently selected
item.

12. void insert(String item, int Inserts the item into this choice
index) at the specified position.

13. protected String paramString() Returns a string representing the


state of this Choice menu.

14. protected void It processes the event on the


processEvent(AWTEvent e) choice.

15. protected void Processes item events occurring


processItemEvent (ItemEvent e) on this Choice menu by
dispatching them to any
registered ItemListener objects.

16. void remove(int position) It removes an item from the


choice menu at the given index
position.

17. void remove(String item) It removes the first occurrence


of the item from choice menu.

18. void removeAll() It removes all the items from the


choice menu.

19. void removeItemListener It removes the mentioned item


(ItemListener l) listener. Thus is doesn't receive
item events from the choice
menu anymore.

20. void select(int pos) It changes / sets the selected


item in the choice menu to the
item at given index position.

21. void select(String str) It changes / sets the selected


item in the choice menu to the
item whose string value is equal
to string specified in the
argument.
Java AWT Choice Example
In the following example, we are creating a choice menu using Choice() constructor. Then we
add 5 items to the menu using add() method and Then add the choice menu into the Frame.
ChoiceExample.java
import java.awt.*;
public class ChoiceExample
{
ChoiceExample()
{
Frame f = new Frame();
Choice c = new Choice();
c.setBounds(100, 100, 75, 75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample();
}
}

Output:

SCROLL BAR
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns. It can be added to top-level
container like Frame or a component like Panel. The Scrollbar class extends the Component class.
AWT Scrollbar Class Declaration
Syntax: public class Scrollbar extends Component implements Adjustable, Accessible
Scrollbar Class Fields
The fields of java.awt.Image class are as follows:
o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.
o static int VERTICAL - It is a constant to indicate a vertical scroll bar.
Scrollbar Class Constructors
Sr. Constructor Description
no.

1 Scrollbar() Constructs a new vertical scroll bar.

2 Scrollbar(int orientation) Constructs a new scroll bar with the specified


orientation.

3 Scrollbar(int orientation, Constructs a new scroll bar with the specified


int value, int visible, int orientation, initial value, visible amount, and
minimum, int maximum) minimum and maximum values.
Where the parameters,
o orientation: specifiey whether the scrollbar will be horizontal or vertical.
o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is moving.
o Maximum: specify the maximum width of track on which scrollbar is moving.
Method Inherited by Scrollbar
The methods of Scrollbar class are inherited from the following classes:
o java.awt.Component
o java.lang.Object
Scrollbar Class Methods
Sr. Method name Description
no.

1. void addAdjustmentListener It adds the given adjustment listener to


(AdjustmentListener l) receive instances of AdjustmentEvent from
the scroll bar.

2. void addNotify() It creates the peer of scroll bar.

3. int getBlockIncrement() It gets the block increment of the scroll bar.

4. int getMaximum() It gets the maximum value of the scroll bar.

5. int getMinimum() It gets the minimum value of the scroll bar.

6. int getOrientation() It returns the orientation of scroll bar.

7. int getUnitIncrement() It fetches the unit increment of the scroll


bar.

8. int getValue() It fetches the current value of scroll bar.

9. int getVisibleAmount() It fetches the visible amount of scroll bar.

10. boolean getValueIsAdjusting() It returns true if the value is in process of


changing where action results are being
taken by the user.

11. protected String paramString() It returns a string representing the state of


Scroll bar.

12. protected void It processes the adjustment event occurring


processAdjustmentEvent on scroll bar by dispatching them to any
(AdjustmentEvent e) registered AdjustmentListener objects.

13. protected void It processes the events on the scroll bar.


processEvent(AWTEvent e)

14. void removeAdjustmentListener It removes the given adjustment listener.


(AdjustmentListener l) Thus it no longer receives the instances of
AdjustmentEvent from the scroll bar.

15. void setBlockIncrement(int v) It sets the block increment from scroll bar.

16. void setMaximum (int It sets the maximum value of the scroll bar.
newMaximum)

17. void setMinimum (int It sets the minimum value of the scroll bar.
newMinimum)

18. void setOrientation (int It sets the orientation for the scroll bar.
orientation)

19. void setUnitIncrement(int v) It sets the unit increment for the scroll bar.
20. void setValue (int newValue) It sets the value of scroll bar with the given
argument value.

21. void setValueIsAdjusting It sets the valueIsAdjusting property to


(boolean b) scroll bar.

22. void setValues (int value, int It sets the values of four properties for
visible, int minimum, int scroll bar: value, visible amount, minimum
maximum) and maximum.

23. void setVisibleAmount (int It sets the visible amount of the scroll bar.
newAmount)

24. AccessibleContext It gets the accessible context related to the


getAccessibleContext() scroll bar.

25. AdjustmentListener[] It returns an array of al lthe adjustment


getAdjustmentListeners() listeners registered on the scroll bar.

26. T[] It returns an array if all objects that are


getListeners(Class listenerType) registered as FooListeners on the scroll bar
currently.
Java AWT Scrollbar Example
In the following example, we are creating a scrollbar using the Scrollbar() and adding it into
the Frame.
ScrollbarExample.java
import java.awt.*;
public class ScrollbarExample
{
ScrollbarExample()
{
Frame f = new Frame("Scrollbar Example");
Scrollbar s = new Scrollbar();
s.setBounds (100, 100, 50, 100);
f.add(s);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollbarExample();
}
}

Output:
BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are
the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class
Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Output:

INPUT EVENT
The InputEvent class is root event class for all component-level input events. Input events are
delivered to listeners before they are processed normally by the source where they originated. This
allows listeners and component subclasses to "consume" the event so that the source will not process
them in their default manner. For example, consuming mousePressed events on a Button component
will prevent the Button from being activated.
Class declaration
Syntax: public abstract class InputEvent extends ComponentEvent
Field
Following are the fields for java.awt.event.InputEvent class:
 static int ALT_DOWN_MASK -- The Alt key extended modifier constant.
 static int ALT_GRAPH_DOWN_MASK -- The AltGraph key extended modifier constant.
 static int ALT_GRAPH_MASK -- The AltGraph key modifier constant.
 static int ALT_MASK -- The Alt key modifier constant.
 static int BUTTON1_DOWN_MASK -- The Mouse Button1 extended modifier constant.
 static int BUTTON1_MASK -- The Mouse Button1 modifier constant.
 static int BUTTON2_DOWN_MASK -- The Mouse Button2 extended modifier constant.
 static int BUTTON2_MASK -- The Mouse Button2 modifier constant.
 static int BUTTON3_DOWN_MASK -- The Mouse Button3 extended modifier constant.
 static int BUTTON3_MASK --The Mouse Button3 modifier constant.
 static int CTRL_DOWN_MASK -- The Control key extended modifier constant.
 static int CTRL_MASK -- The Control key modifier constant.
 static int META_DOWN_MASK -- The Meta key extended modifier constant.
 static int META_MASK -- The Meta key modifier constant.
 static int SHIFT_DOWN_MASK -- The Shift key extended modifier constant.
 static int SHIFT_MASK -- The Shift key modifier constant.
Class methods
S.No. Method & Description

1 void consume()
Consumes this event so that it will not be processed in
the default manner by the source which originated it.

2 int getModifiers()
Returns the modifier mask for this event.

3 int getModifiersEx()
Returns the extended modifier mask for this event.

4 static String getModifiersExText(int modifiers)


Returns a String describing the extended modifier keys
and mouse buttons, such as "Shift", "Button1", or
"Ctrl+Shift".

5 long getWhen()
Returns the timestamp of when this event occurred.

6 boolean isAltDown()
Returns whether or not the Alt modifier is down on this
event.

7 boolean isAltGraphDown()
Returns whether or not the AltGraph modifier is down on
this event.

8 boolean isConsumed()
Returns whether or not this event has been consumed.

9 boolean isControlDown()
Returns whether or not the Control modifier is down on
this event.
10 boolean isMetaDown()
Returns whether or not the Meta modifier is down on this
event.

11 boolean isShiftDown()
Returns whether or not the Shift modifier is down on this
event.
Methods inherited
This class inherits methods from the following classes:
 java.awt.event.ComponentEvent
 java.awt.AWTEvent
 java.util.EventObject
 java.lang.Object

MENUS
The object of Menu class is a pull down menu component which is displayed on the menu bar.
It inherits the MenuItem class.
AWT Menu class declaration

Syntax: public class Menu extends MenuItem implements MenuContainer, Accessible


EXAMPLE
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy