Java New Syllabus Notes
Java New Syllabus Notes
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.
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.
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.
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
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
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
"javatpoint" String
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 = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
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 */.
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);
}
}
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
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.
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
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
//|| vs |
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.
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.
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;
}
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.
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:
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
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.
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]
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
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
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.
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
offsetByCodePoints() Returns the index within this String that is offset int
from the given index by codePointOffset code
points
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.
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.
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.
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
//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
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 −
THREAD METHODS
Following is the list of important methods available in the Thread class.
S.No. Method & Description
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
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
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:
PrintWriter This contains the most used print() and println() method
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
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>
*/
Example
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to Apoorva”,50,50);
}
}
OUTPUT
Sorry! you need Java to see this
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
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
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
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;
}
public void setSize(int width, int Sets the size (width and height) of
height) the component.
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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.
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.
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
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 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.
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.
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.
12. void insert(String item, int Inserts the item into this choice
index) at the specified position.
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.
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.
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)
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.
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
Output: