Java Notes 3 - TutorialsDuniya
Java Notes 3 - TutorialsDuniya
COM
Java Programming
Notes
Contributor: Abhishek Sharma
[Founder at TutorialsDuniya.com]
UNIT – 1
1. INTRODUCTION TO OOP.
m
2. NEED OF OOP.
co
3. PRINCIPLES OF OBJECT ORIENTED LANGUAGES.
a.
4. PROCEDURAL LANGUAGES Vs OOP.
5. APPLICATIONS OF OOP.
iy
un
6. HISTORY OF JAVA.
sD
8. JAVA FEATURES.
ri
9. PROGRAM STRUCTURES.
to
10.INSTALLATION OF JDK1.6.
Tu
Page 1
1. INTRODUCTION TO OOP.
m
A distinguishing feature of objects is that an object's procedures can access and
often modify the data fields of the object with which they are associated (objects
have a notion of "this").
co
In object-oriented programming, computer programs are designed by making
them out of objects that interact with one another. There is significant diversity in
object-oriented programming, but most popular languages are class-based,
a.
meaning that objects are instances of classes, which typically also determines
their type.
Many of the most widely used programming languages are multi-paradigm
iy
programming languages that support object-oriented programming to a greater or
lesser degree, typically in combination with imperative, procedural programming.
Significant object-oriented languages include C++, Objective-
un
C, Smalltalk, Delphi, Java, C#, Perl, Python, Ruby and PHP.
Objects sometimes correspond to things found in the real world. For example, a
graphics program may have objects such as "circle," "square," "menu."
sD
An online shopping system will have objects such as "shopping cart," "customer,"
and "product." The shopping system will support behaviors such as "place order,"
"make payment," and "offer discount."
Objects are designed in class hierarchies. For example, with the shopping system
al
there might be high level classes such as "electronics product," "kitchen product,"
and "book."
There may be further refinements for example under "electronic products": "CD
ri
2. NEED OF OOP
Tu
When we are going to work with classes and objects we always think why there is
need of classes and object although without classes and objects our code works
well. But after some work on classes and objects we think, it’s better to work with
classes and objects.
And then we can understand that Object oriented Programming is better than
procedural Programming. Object oriented programming requires a different way
of thinking about how can we construct our application.
Page 2
m
in different modules called classes. And one class is separate from other classes .It
has its own functionality and features.
co
So what advantages we can get from Object Oriented Programming:
1: Reusability Of Code: In object oriented programming one class can easily copied to
a.
another application if we want to use its functionality,
EX: When we work with hospital application and railway reservation application .In
iy
both application we need person class so we have to write only one time the person class
and it can easily use in other application.
un
2: Easily Discover a bug: When we work with procedural programming it take a lot of
time to discover a bug and resolve it .But in object Oriented Programming due to
modularity of classes we can easily discover the bug and we have to change in one class
sD
only and this change make in all the application only by changing it one class only.
al
The Objects Oriented Programming (OOP) is constructed over four major principles:
to
1. Encapsulation,
2. Data Abstraction,
3. Polymorphism
Tu
4. Inheritance.
1. Encapsulation:
Encapsulation means that the internal representation of an object is generally hidden from
view outside of the object’s definition. Typically, only the object’s own methods can
directly inspect or manipulate its fields.
Page 3
An accessor is a method that is used to ask an object about itself. In OOP, these are
usually in the form of properties, which have a get method, which is an accessor method.
However, accessor methods are not restricted to properties and can be any public method
m
that gives information about the state of the object.
co
A Mutator is public method that is used to modify the state of an object, while hiding the
implementation of exactly how the data gets modified. It’s the set method that lets the
caller modify the member data behind the scenes.
a.
Hiding the internals of the object protects its integrity by preventing users from setting
iy
the internal data of the component into an invalid or inconsistent state. This type of data
protection and implementation protection is called Encapsulation.
A benefit of encapsulation is that it can reduce system complexity.
un
Abstraction
Data abstraction and encapsulation are closely tied together, because a simple
sD
actual item.
According to Graddy Booch, “An abstraction denotes the essential characteristics
ri
of an object that distinguish it from all other kinds of object and thus provide
crisply defined conceptual boundaries, relative to the perspective of the viewer.”
to
that contains the same essential properties and actions we can find in the original
object we are representing.
Page 4
In classical inheritance where objects are defined by classes, classes can inherit attributes
and behaviour from pre-existing classes called base classes, super classes, parent classes
or ancestor classes.
The resulting classes are known as derived classes, subclasses or child classes. The
relationships of classes through inheritance give rise to a hierarchy.
m
4.Polymorphism
Polymorphism means one name, many forms. Polymorphism manifests itself by having
co
multiple methods all with the same name, but slightly different functionality.
There are 2 basic types of polymorphism.
Overriding, also called run-time polymorphism. For method overloading, the compiler
a.
determines which method will be executed, and this decision is made when the code gets
compiled.
iy
Overloading, which is referred to as compile-time polymorphism. Method will be
used for method overriding is determined at runtime based on the dynamic type of an
object.
un
4. PROCEDURAL LANGUAGES Vs OOP
sD
When programming any system you are essentially dealing with data and the code that
change that data. These two fundamental aspects of programming are handled quite
al
differently in procedural systems compared with object oriented systems, and these
differences require different strategies in how we think about writing code.
ri
Procedural programming
to
In procedural programming our code is organized into small procedures that use
and change our data. We write our procedures as either custom tags or functions.
Tu
These functions typically take some input, do something, and then produce some
output. Ideally your functions would behave as "black boxes" where input data
goes in and output data comes out.
Page 5
The key idea here is that our functions have no intrinsic relationship with the data
they operate on. As long as you provide the correct number and type of arguments,
the function will do its work and faithfully return its output.
Sometimes our functions need to access data that is not provided as a parameter,
i.e., we need access data that is outside the function. Data accessed in this way is
m
considered "global" or "shared" data.
co
a.
iy
un
So in a procedural system our functions use data they are "given" (as parameters) but also
sD
In object oriented programming, the data and related functions are bundled
together into an "object". Ideally, the data inside an object can only be
ri
functions provide the only means of doing something with that data. In a
well designed object oriented system objects never access shared or global
Tu
data, they are only permitted to use the data they have, or data they are
given.
Page 6
m
co
Global and shared data
We can see that one of the principle differences is that procedural systems make
a.
use of shared and global data, while object oriented systems lock their data privately
away in objects.
iy
Let's consider a scenario where you need to change a shared variable in a
procedural system. Perhaps you need to rename it, change it from a string to a numeric,
change it from a struct to an array, or even remove it completely.
un
In a procedural application you would need to find and change each place in the
code where that variable is referenced. In a large system this can be a widespread and
difficult change to make.
sD
al
ri
to
In an object oriented system we know that all variables are inside objects and that
Tu
only functions within those objects can access or change those variables. When a variable
needs to be changed then we only need to change the functions that access those variables.
As long as we take care that the functions' input arguments and output types are
not changed, then we don't need to change any other part of the system.
Page 7
m
co
5. APPLICATIONS OF OOP.
a.
Applications of OOP are beginning to gain importance in many areas. The most
iy
important application is user interface design. Real business systems are more complex
and contain many attributes and methods, but OOP applications can simplify a complex
problem.
un
Application areas:
sD
Computer animation
To design Compiler
To access relational data base
To develop administrative tools and system tools
al
-
to
Real Time Systems : A real time system is a system that give output at given instant
and its parameters changes at every time. A real time system is nothing but a dynamic
system. Dynamic means the system that changes every moment based on input to the
system.
OOP approach is very useful for Real time system because code changing is very easy in
OOP system and it leads toward dynamic behavior of OOP codes thus more suitable to real
Page 8
timeSystem
SimulationAndModeling:-
System modeling is another area where criteria for OOP approach is countable.
Representing a system is very easy in OOP approach because OOP codes are very easy to
understand and thus is preferred to represent a system in simpler form.
HypertextAndHypermedia:-
m
Hypertext and hypermedia is another area where OOP approach is spreading its legs. Its
ease of using OOP codes that makes it suitable for various media approaches.
co
DecisionSupportSystem:-
Decision support system is an example of Real time system that too very advance and
complex system. More details is explained in real time system
a.
CAM/CAE/CAD System:-
Computer has wide use of OOP approach. This is due to time saving in writing OOP codes
iy
and dynamic behavior of OOP codes.
Office AutomationSystem:-
Automation system is just a part or type of real time system. Embedded systems make it
easy to use
un OOP for automated system.
AIAndExpertSystem:-
It is mixed system having both hypermedia and real time system.
sD
6 .HISTORY OF JAVA.
Java history is interesting to know. The history of java starts from Green Team. Java
team members (also known as Green Team), initiated a revolutionary task to develop a
language for digital devices such as set-top boxes, televisions etc.
to
For the green team members, it was an advance concept at that time. But, it was suited for
Tu
Page 9
James Gosling
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
m
project in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top
co
boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
a.
4) After that, it was called Oak and was developed as a part of the Green project.
iy
un
sD
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
ri
7) Why they choose java name for java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt",
Tu
"DNA" etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since
java was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
Page 10
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
m
12) JDK 1.0 released in (January 23, 1996).
co
There are many java versions that have been released. Current stable release of Java is
Java SE 8.
a.
1. JDK Alpha and Beta (1995)
iy
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
un
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
sD
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
What is JVM?
It is:
Page 11
m
What it does?
co
The JVM performs following operation:
Loads code
Verifies code
a.
Executes code
Provides runtime environment
iy
Internal Architecture of JVM un
Let's understand the internal architecture of JVM. It contains class loader, memory area,
execution engine etc.
sD
al
ri
to
Tu
1) Class loader:
Page 12
2) Class (Method) Area: Class (Method) Area stores per-class structures such as the
runtime constant pool, field and method data, the code for methods.
3) Heap:
m
4) Stack:
Java Stack stores frames .It holds local variables and partial results, and plays a part in
method invocation and return.
co
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
a.
method invocation completes.
iy
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.
un
6) Native Method Stack:
sD
It contains all the native methods used in the application.
7) Execution Engine:
It contains:
al
1) Virtual processor
It is used to improve the performance. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time needed for
compilation.
Tu
Here the term? Compiler? Refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
Page 13
8. JAVA FEATURES.
There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.
m
1. Simple
2. Object-Oriented
3. Platform independent
co
4. Secured
5. Robust
6. Architecture neutral
a.
7. Portable
8. Dynamic
iy
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
un
Simple
According to Sun, Java language is simple because:
sD
syntax is based on C++ (so easier for programmers to learn it after C++).
Collection in java.
Object-oriented
to
Page 14
5. Abstraction
6. Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides software-based
m
platform.
The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms .It has two components:
co
1. Runtime Environment.
2. API (Application Programming Interface).
a.
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, and
Mac/OS etc. Java code is compiled by the compiler and converted into byte code.
iy
This byte code is a platform independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere (WORA).
un
Secured
Java is secured because:
No explicit pointer.
sD
Robust
Robust simply means strong. Java uses strong memory management. There is lack of
al
There is automatic garbage collection in java. There is exception handling and type
ri
Architecture-neutral
to
Portable
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++).
Page 15
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine
on the internet.
m
Multi-threaded
co
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it shares the same memory. Threads are important for multi-media,
a.
Web applications etc.
9.PROGRAM STRUCTURES.
iy
Description:
Let’s use example of HelloWorld Java program to understand structure and features of
un
class. This program is written on few lines, and its only task is to print “Hello World
from Java” on the screen.
Refer the following picture:
sD
al
ri
to
Tu
1. “package sct”:
It is package declaration statement. The package statement defines a name space in which
classes are stored. Package is used to organize the classes based on functionality. If you
Page 16
omit the package statement, the class names are put into the default package, which has
no name. Package statement cannot appear anywhere in program. It must be first line of
your program or you can omit it.
m
a. public: This is access modifier keyword which tells compiler access to class. Various
values of access modifiers can be public, protected, and private or default (no value).
b. class: This keyword used to declare class. Name of class (Hello World) followed by
co
this keyword.
3. Comments section:
a.
We can write comments in java in two ways.
a. Line comments: It start with two forward slashes (//) and continue to the end of the
current line. Line comments do not require an ending symbol.
iy
b. Block comments start with a forward slash and an asterisk (/*) and end with an
asterisk and a forward slash (*/).Block comments can also extend across as many lines as
needed.
un
4. “public static void main (String [ ] args)”:
Its method (Function) named main with string array as argument.
sD
c. println:It is utility method name which is used to send any String to console.
d. “Hello World from Java”: It is String literal set as argument to println method.
Tu
Page 17
The following tasks provide the information you need to install JDK software and
set JAVA_HOME on UNIX or Windows systems.
Microsoft Windows
m
JDK6: At least release 1.6.0_03
co
Caution –
It is not recommended to user JDK 1.6.0_13 or 1.6.0_14 with Java CAPS due to
issues with several of the wizards used to develop applications. In addition, the
a.
installation fails on Windows when using JDK 1.6.0_13 or 1.6.0_14. The Java CAPS
Installer does not support JDK release 1.6.0_04 in the 64–bit version on Solaris SPARC
iy
or AMD 64–bit environments. The installer also does not support JDK 1.6.0 or later on
AIX 5.3. un
To Install the JDK Software and Set JAVA_HOME on a Windows System
sD
2. To set JAVA_HOME:
a. Right click My Computer and select Properties.
to
Page 18
UNIT – II
1. VARIABLES
2. PRIMITIVE DATA TYPES
3. IDENTIFIERS – NAMING CONVENTIONS
4. KEYWORDS
m
5. LITERALS
6. OPERATORS
7. EXPRESSIONS
co
8. PRECEDENCE RULES & ASSOCIATIVITY
9. TYPE CONVERSION & TYPE CASTING
10. BRANCHING
11. CONDITIONAL STATEMENTS
a.
12. LOOPS
13. CLASSES
14. OBJECTS
iy
15. METHODS
16. CONSTRUCTIORS
17. CONSTRUCTIOR OVERLOADING
un
18. GARBAGE COLLECTOR
19. STATIC KEYWORD
20. THIS KEYWORD
21. ARRAYS
sD
Page 1
VARIABLES
Variable is name of reserved area allocated in memory.
m
Ex: int data=50;//Here data is variable
co
Types of Variables
There are three types of variables in java
a.
local variable
instance variable
static variable
iy
Local Variable
un
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance
sD
Static variable
A variable that is declared as static is called static variable. It cannot be local.
al
DATA TYPES
“Data types are used for representing the data in main memory of the computer.
Page 2
m
co
a.
iy
un
In JAVA, we have eight data types which are organized in four groups. They are
integer category data types, float category data types, character category data
types and Boolean category data types.
sD
1. Integer category data types: These are used to represent integer data.
This category of data type contains four data types which are given in the
following table:
al
Page 3
2. Float category data types: Float category data types are used for
representing the data in the form of scale, precision i.e., these category
data types are used for representing float values. This category contains
two data types; they are given in the following table:
No of
Type Contains Default Size Range
m
decimals
Float IEEE 754 0.0f 32 1.4E-45 to 8
floating bit 3.4028235E+38
co
point or
single- 4
precision bytes
a.
double IEEE 754 0.0d 64 439E-324 to 16
floating bit 1.7976931348623157E+308
point or
iy
double- 8
precision bytes
un
3. CHAR:
char data type is a single 16-bit Unicode character.
sD
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'
al
2. Identifiers can contain only the special characters Underscore (_), Dollar ($).
Page 4
m
6. Identifiers are case sensitive.
co
Ex: Car, CAR, car, cAR, CaR
a.
KEYWORDS
Keywords are special tokens in the language which have reserved use in the
iy
language. Keywords may not be used as identifiers in Java — you cannot declare a
field whose name is a keyword, for instance.
un
Examples of keywords are the primitive types, int and boolean; the control flow
statements for and if; access modifiers such as public, and special words which
mark the declaration and definition of Java classes, packages, and interfaces:
sD
class, package, interface.
Below are all the Java language keywords:
LITERALS
m
A literal is the source code representation of a fixed value.Literals in Java are a
sequence of characters (digits, letters, and other characters) that represent constant
co
values to be stored in variables.
Java language specifies five major types of literals. Literals can be any number, text,
or other information that represents a value.
a.
This means what you type is what you get. We will use literals In addition to
variables in Java statement.
iy
While writing a source code as a character sequence, we can specify any value as a
literal such as an integer.
un
They are:
Integer literals
sD
Floating literals
Character literals
al
String literals
Boolean literals
ri
Each of them has a type associated with it. The type describes how the values
behave and how they are stored.
to
Integer literals:
Integer data types consist of the following primitive data types: int, ong, byte, and
Tu
short. Byte, int, long, and short can be expressed in decimal (base 10), hexadecimal
(base 16) or octal (base 8) number systems as well. Prefix 0 is used to indicate octal
and prefix 0x indicates hexadecimal when using these number systems for literals.
Examples:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
Page 6
Floating-point literals:
Floating-point numbers are like real numbers in mathematics, for example,
4.13179, -0.000001.
Java has two kinds of floating-point numbers: float and double. The default
type when you write a floating-point literal is double, but you can designate it
explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended
to designate the data type of a floating-point literal as float. We can also specify a
m
floating-point literal in scientific notation using Exponent (short E ore), forinstance:
the double literal 0.0314E2 is interpreted as: 0.0314 *10² (i.e 3.14). 6.5E+32 (or
6.5E32) Double-precision floating-point literal 7D Double-precision floating-point
literal .01f Floating-point literal
co
Character literals:
char data type is a single 16-bit Unicode character. We can specify a character literal
a.
as asingle printable character in a pair of single quote characters such as 'a', '#', and
'3'. You must know about the ASCII character set. The ASCII character set includes
128 characters including letters, numerals, punctuation etc. Below table shows a set
iy
of these special characters.
Escape Meaning
\n
un
New line
\t Tab
\b Backspace
\r Carriage return
sD
\f Formfeed
\\ Backslash
\' Single quotation mark
\" Double quotation mark
al
\d Octal
\xd Hexadecimal
\ud Unicode character
ri
String Literals:
The set of characters in represented as String literals in Java. Always use "double
quotes" for String literals. There are few methods provided in Java to
combine strings, modify strings and to know whether to strings have the same
values.
"" The empty string
"\"" A string containing
m
"This is a string" A string containing 16 characters
actually a string-valued constant expression, formed
"This is a " + "two-line string"
from two string literals
co
Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the
Null literal in the source code as 'null'. To reduce the number of references to an
a.
object, use null literal.
The type of the null literal is always null. We typically assign null literals to object
reference variables. For instance
iy
s = null;
Boolean Literals:
un
The values true and false are treated as literals in Java programming. When we
assign a value to a boolean variable, we can only use these two values. Unlike C,
We can't presume that the value of 1 is equivalent to true and 0 is equivalent to false
in Java. We have to use the values true and false to represent a Boolean value.
sD
Example
boolean chosen = true;
al
JAVA OPERATORS:
ri
Types of Operators:
1. Assignment Operator
2. Arithmetic Operator
3. Unary Operators
Page 8
4. Relational Operator
5. Conditional Operators
m
Operators Precedence
co
unary ++expr --expr +expr -expr ~ !
a.
iy
multiplicative */%
+-
un
additive
shift
equality == !=
ri
to
bitwise exclusive OR ^
bitwise inclusive OR |
Page 9
logical OR ||
m
ternary ?:
co
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
a.
1. Java Assignment Operator:
iy
“Assignment Operator” is binary Operator as it operates on two operands.
un
It have two values associated with it i.e Left Value and Right Value.
Array Variable
Object
Syntax and Example:
int javaProgramming; //Default Assignment
al
Ways of Assignment:
Way 1 : Declare and Assign
to
class AssignmentDemo {
Tu
System.out.println(ivar);
}
}
Page 10
class AssignmentDemo {
m
public static void main (String[] args){
co
System.out.println(ivar);
}
}
a.
iy
Way 3 : Assignment & Arithmetic Operation
class AssignmentAndArithmetic {
un
public static void main (String[]
System.out.println(num1);
al
}
}
ri
Page 11
m
Example 1 : Arithmetic Operators
class ArithmeticOperationsDemo
co
{ public static void main (String[]
args){
a.
// answer is now 3
iy
int answer = 1 + 2;
System.out.println(answer);
un
// answer is now 2
answer = answer - 1;
System.out.println(answer);
// answer is now 4
sD
answer = answer * 2;
System.out.println(answer);
// answer is now 2
al
answer = answer / 2;
System.out.println(answer);
ri
// answer is now 10
answer = answer + 8;
to
// answer is now 3
answer = answer % 7;
System.out.println(answer);
Tu
}
}
Page 12
class ModulusOperatorDemo {
public static void main(String args[])
{ int x = 92;
double y = 92.25;
m
System.out.println("y mod 10 = " + y % 10);
}
}
co
Output :
x mod 10 = 2
y mod 10 = 2.25
a.
iy
Example : Arithmetic Compound Assignment Operators in Java
class CompoundAssignmentDemo
un
{ public static void main(String args[])
{ int a = 1;
int b = 2;
int c = 3;
sD
a += 1;
b *= 1;
c %= 1;
al
Output :
Tu
a=2
b=2
c=0
Page 13
m
a = 0011 1100
co
b = 0000 1101
-----------------
a.
a&b = 0000 1100
iy
a|b = 0011 1101
Operator Result
~ Bitwise unary NOT
Bitwise AND
al
&
| Bitwise OR
ri
^ Bitwise exclusive OR
to
Page 14
|= Bitwise OR assignment
m
>>= Shift right assignment
co
>>>= Shift right zero fill assignment
a.
Bitwise Operators : Bitwise unary NOT
iy
Bitwise Unary Not is also called as bitwise complement.
It is Unary Operator because it operates on single Operand.
un
Unary Not Operator is denoted by – ‘~‘.
The Unary NOT operator inverts all of the bits of its operand.
Example 1 : Bitwise unary NOT : Bitwise Operators
sD
class BitwiseNOT{
public static void main(String
args[]){ int ivar =42;
System.out.println("~ ivar = " + ~ivar);
}
al
}
Output :
~ ivar = -43
ri
Page 15
class BitwiseNOT{
public static void main(String
args[]){ System.out.println("~ 0 = " + ~0);
System.out.println("~ 1 = " + ~1);
System.out.println("~ 2 = " + ~2);
System.out.println("~ 3 = " + ~3);
}
}
m
Output :
~ 0 = -1
~ 1 = -2
co
~ 2 = -3
~ 3 = -4
Bitwise AND Operator is –
Binary Operator as it Operates on 2 Operands.
a.
Denoted by – &
Used for : Masking Bits.
iy
Bitwise AND Summary Table :
un
A B A&B
0 0 0
0 1 0
sD
1 0 0
1 1 1
class BitwiseAND{
public static void main(String args[]){
ri
}
}
Output :
AND Result = 10
Explanation of Code :
Page 16
Num1 : 00101010 42
Num2 : 00001111 15
======================
AND : 00001010 10
42 is represented in Binary format as -> 00101010
15 is represented in Binary format as -> 00001111
According to above rule (table) we get 00001010 as final structure.
m
println method will print decimal equivalent of 00001010 and display it on screen.
Bitwise OR Operator is –
co
The OR operator, |, combines bits such that if either of the bits in the
operands is a 1, then the resultant bit is a 1
Binary Operator as it Operates on 2 Operands.
a.
Denoted by – |
Bitwise OR Summary Table :
A B A|B
iy
0 0 0
0 1 1
1 0
un
1
1 1 1
class BitwiseOR {
public static void main(String args[]){
}
to
}
Output :
OR Result = 47
Tu
Explanation of Code :
Num1 : 00101010 42
Num2 : 00001111 15
======================
OR : 00101111 47
42 is represented in Binary format as -> 00101010
Page 17
The XOR operator (^) combines bits such that if either of the bits in the
m
operands is a 1, then the resultant bit is a 1
Binary Operator as it Operates on 2 Operands.
Denoted by : ^
co
Bitwise XOR Summary Table :
a.
A B A^B
0 0 0
iy
0 1 1
1 0 1
1 1 0
un
Example 1 : XORing 42 and 15
class BitwiseXOR {
public static void main(String args[]){
sD
}
ri
}
to
Output :
Tu
XOR Result = 37
Explanation of Code :
Num1 : 00101010 42
Num2 : 00001111 15
======================
XOR : 00100101 37
42 is represented in Binary format as -> 00101010
Page 18
m
The first is a quantity to be shifted, and the second specifies the number of
bit positions by which the first operand is to be shifted.
co
The direction of the shift operation is controlled by the operator used. Shift
operators convert their operands to 32 or 64 bits and return a result of the
same type as the left operator.
a.
Shift Operators
Operator Name Use Description
iy
<< Shift left op1 << op2 Shifts bits of op1 left by distance op2; fills
with 0 bits on the right side
>> Shift right op1 >> op2 Shifts bits of op1 right by distance op2; fills with
un
highest (sign) bit on the left side
>>> op1 >>> op Shifts bits of op1 right by distance op2; fills
Shift right 2 with 0 bits on the left side
sD
zero fill
Shifting is basically taking the binary equivalent of a number and moving the bit
pattern left or right.
al
Example:
ri
class Bit{
public static void main(String []args)
to
{
int a =2;
System.out.println(" rightshift by 1 is:" +(a>>1));
System.out.println(" leftshift by 1 is:" +(a<<1));
Tu
C:\>java Bit
rightshift by 1 is:1
Page 19
leftshift by 1 is:4
Shift right zero fill by 1 is:1
m
public class Bitwise_assign {
public static void main(String args[])
{ int a = 1;
co
int b = 2;
int c = 3;
a |= 4;
a.
b >>= 1;
c <<= 1;
a ^= c;
iy
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
un
}
}
OutPut:
sD
C:\>javac Bitwise_assign.java
C:\>java Bitwise_assign
al
a=3
b=1
c=6
ri
Unary Plus
Unary Minus
Logical Compliment Operator
Increment Operator
Decrement Operator
Page 20
class UnaryDemo {
m
int result = +1;
System.out.println(result);
co
// result is now -1
result = -result;
System.out.println(result);
a.
// false
boolean success = false;
System.out.println(success);
iy
// true
System.out.println(!success);
un
}
}
sD
Out Put:
C:\>javac UnaryDemo.java
al
C:\>java UnaryDemo
1
-1
ri
false
true
to
Page 21
Syntax :
m
Example:
class Inc_Dec {
public static void main(String args[])
co
{ int num1 = 1;
int num2 = 1;
num1++;
a.
num2++;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
iy
++num1;
++num2;
System.out.println("num1 = " + num1);
un
System.out.println("num2 = " + num2);
num1--;
num2--;
System.out.println("num1 = " + num1);
sD
System.out.println("num2 = " + num2);
--num1;
--num2;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
al
}
}
ri
to
OutPut:
C:\>javac Inc_Dec.java
Tu
C:\>java Inc_Dec
num1 = 2
num2 = 2
num1 = 3
num2 = 3
num1 = 2
num2 = 2
Page 22
num1 = 1
num2 = 1
5. Logical Operators:
Every programming language has its own logical operators, or at least a way of
expressing logic. Java's logical operators are split into two subtypes,
relational and conditional.
m
Relational Operators in Java Programming:
co
Relational Operators are used to check relation between two variables or
numbers.
Relational Operators are Binary Operators.
a.
Relational Operators returns “Boolean” value .i.e it will return true or false.
Most of the relational operators are used in “If statement” and inside Looping
statement in order to check truthness or falseness of condition.
iy
un
sD
al
ri
Logical Operators:
to
There are four logical operators in Java, however one of them is less commonly used
and I will not discuss here. It's really optional compared to the ones I will introduce,
and these will be a whole heck of a lot useful to you now.
Tu
Page 23
Example:
m
System.out.println("j = " + j);
System.out.println("i > j is " + (i > j));
System.out.println("i < j is " + (i < j));
co
System.out.println("i >= j is " + (i >= j));
System.out.println("i <= j is " + (i <= j));
System.out.println("i == j is " + (i == j));
System.out.println("i != j is " + (i != j));
a.
System.out.println("(i < 10) && (j < 10) is " + ((i < 10) && (j<
iy
10)));
System.out.println("(i < 10) || (j < 10) is " + ((i < 10) || (j<
10)));
}
un
}
sD
Out Put:
C:\>javac MainClass.java
C:\>java MainClass
i=5
al
j=6
i > j is false
i < j is true
ri
i >= j is false
i <= j is true
i == j is false
to
i != j is true
(i < 10) && (j < 10) is true
(i < 10) || (j < 10) is true
Tu
6. Ternary operator:
Ternary operator is also known as the Conditional operator. This operator
consists of three operands and is used to evaluate Boolean expressions. The goal of
the operator is to decide which value should be assigned to the variable. The
operator is written as:
Page 24
Example:
public class Ternary {
public static void main(String
args[]){ int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
m
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
co
}
}
a.
OutPut:
iy
C:\>javac Ternary.java
C:\>java Ternary
Value of b is : 30
un
Value of b is : 20
Expressions
sD
Page 25
m
of expressions.
The operators are shown with decreasing precedence from the top of the
co
table.
Operators within the same row have the same precedence.
Parentheses, ( ), can be used to override precedence and associativity.
a.
The unary operators, which require one operand, include the postfix
increment (++) and decrement (--) operators from the first row, all the prefix
iy
operators (+, -, ++, --, ~, !) in the second row, and the prefix operators (object
creation operator new, cast operator (type)) in the third row.
un
The conditional operator (? :) is ternary, that is, requires three operands.
All operators not listed above as unary or ternary, are binary, that is, require
two operands.
sD
All binary operators, except for the relational and assignment operators,
associate from left to right. The relational operators are nonassociative.
Except for unary postfix increment and decrement operators, all unary
operators, all assignment operators, and the ternary conditional operator
al
first if there are two operators with different precedence, and these follow
each other in the expression. In such a case, the operator with the highest
precedence is applied first.
to
Page 26
m
In order to understand the result returned by an operator, it is important to
understand theevaluation order of its operands. Java states that the operands of
co
operators are evaluated from left to right.
Java guarantees that all operands of an operator are fully evaluated before the
operator is applied. The only exceptions are the short-circuit conditional
a.
operators &&, ||, and ?:.
In the case of a binary operator, if the left-hand operand causes an exception the
iy
right-hand operand is not evaluated. The evaluation of the left-hand operand can
have side effects that can influence the value of the right-hand operand. For example,
in the following code:
un
int b = 10;
System.out.println((b=3) + b);
The value printed will be 6 and not 13. The evaluation proceeds as follows:
sD
(b=3) + b
3 + b b is assigned the value 3
al
3+3
6
The evaluation order also respects any parentheses, and the precedence and
ri
returned by an operator.
Page 27
++ pre-increment
-- pre-decrement
+ unary plus
2 right to left
- unary minus
! logical NOT
~ bitwise NOT
m
() cast
3 right to left
co
new object creation
a.
/ Multiplicative 4 left to right
%
iy
+- additive string
5 left to right
+ concatenation
un
<< >>
Shift 6 left to right
>>>
sD
< <=
> >= relational
7 left to right
instanceof type comparison
al
==
Equality 8 left to right
!=
ri
Page 28
m
Java Data Type Casting Type Conversion
co
Summary: By the end of this tutorial "Java Data Type Casting Type Conversion", you
will be comfortable with converting one data type to another either implicitly or
explicitly.
a.
Java supports two types of castings – primitive data type casting and reference
type casting. Reference type casting is nothing but assigning one Java object to
iy
another object. It comes with very strict rules and is explained clearly in Object
Casting. Now let us go for data type casting.
un
Java data type casting comes with 3 flavors.
1. Implicit casting
2. Explicit casting
3. Boolean casting.
sD
A data type of lower size (occupying less memory) is assigned to a data type of
al
higher size. This is done implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.
ri
Examples:
In the above code 4 bytes integer value is assigned to 8 bytes double value.
Example:
Page 29
m
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
co
}
}
Out Put:
a.
Int value 100
Long value 100
iy
Float value 100.0 un
2. Explicit casting (narrowing conversion)
A data type of higher size (occupying more memory) cannot be assigned to a data
sD
type of lower size. This is not done implicitly by the JVM and requires explicit
casting; a casting operation to be performed by the programmer. The higher size is
narrowed to lower size.
In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises
ri
double x = 10.5;
to
int y = (int) x;
The double x is explicitly converted to int y. The thumb rule is, on both sides, the
Tu
Page 30
m
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
co
}
}
Out Put:
a.
Double value 100.04
iy
Long value 100
Int value 100
un
3. Boolean casting
A boolean value cannot be assigned to any other data type. Except boolean, all the
sD
remaining 7 data types can be assigned to one another either implicitly or explicitly;
but boolean cannot. We say, boolean is incompatible for conversion. Maximum we
can assign a boolean value to another boolean.
boolean x = true;
int y = x; // error
ri
boolean x = true;
int y = (int) x; // error
to
byte –> short –> int –> long –> float –> double
In the above statement, left to right can be assigned implicitly and right to left
Tu
requires explicit casting. That is, byte can be assigned to short implicitly but
short to byte requires explicit casting.
Page 31
double d2 = 66.0;
char ch2 = (char) d2;
m
System.out.println(ch2); // prints B
}
}
co
Pass your comments for the betterment of this tutorial "Java Data Type Casting Type
Conversion".
a.
Your one stop destination for all data type conversions
iy
short TO byte int long float double char boolean
int TO byte short long float double char boolean
float TO byte short int
un long double char boolean
double TO byte short int long float char boolean
char TO byte short int long float double boolean
boolean TO byte short int long float double char
sD
the statements were executed line by line from the top to bottom in anorder.
Nowhere were any statements skipped or a statement executed more than
once. We will now look into how this can be achieved using control
Tu
structures.
Java control statements cause the flow of execution to advance and branch
based on the changes to the state of the program.
Control statements are divided into three groups:
Page 32
Selection Statements
Java selection statements allow to control the flow of program‘s execution
m
based upon conditions known only during run-time.
Java provides four selection statements:
co
1) if
2) if-else
3) if-else-if
a.
4) switch
if
Statement(s) between the set of curly braces ‘{ }’ will be executed only if the
iy
condition(s), between the set of brackets ‘( )’ after ‘if’ keyword, is/are true.
Syntax:
un
if (Condition) {
// statements;
}
sD
if-else
If the condition(s) between the brackets ‘( )’ after the ‘if’ keyword is/are true then
the statement(s) between the immediately following set of curly braces ‘{ }’ will be
al
executed else the statement(s) under, the set of curly braces after the ‘else’ keyword
will be executed.
ri
Example:
Syntax:
if (condition) {
to
// statements;
}
else {
Tu
// statements;}
class Example_if_else
{
public static void main(String Args[])
{
if( a > b)
Page 33
{
System.out.println("A = " + a + "\tB = " + b);
System.out.println("A is greater than B");
}
else
{
System.out.println("A = " + a + "\tB = " + b);
System.out.println("Either both are equal or B is greater");
m
}
}
}
co
class Example_nested_if _else
{
public static void main(String Args[])
a.
{
int a = 3;
if (a <= 10 && a > 0)
iy
{
System.out.println("Number is valid.");
if ( a < 5)
un
System.out.println("From 1 to 5");
else
System.out.println("From 5 to 10");
}
sD
else
System.out.println("Number is not valid");
}
}
al
class Example_if_elseif_else
{
ri
else if (a < 0 )
System.out.println("A is a negative value");
else if (a > 0)
System.out.println ("A is a positive value");
else
System.out.println ("A is equal to zero");
}
}
Page 34
switch
When there is a long list of cases & conditions, then if/if-else is not good choice as
the code would become complicated.
Syntax:
switch (expression)
m
{
case value1:
//statement;
co
break;
case value2:
//statement;
break;
a.
default:
//statement;
}
iy
The moment user enters his choice, it will be matched with the cases’ names &
program execution will jump to the matching ‘Case’ & the statement under that case
un
will be executed till the keyword ‘break’ comes. It is very important else the other
unwanted cases will also get executed. After the last case there is ‘default’ keyword.
Statements between ‘default:’ and the closing bracket of switch-case region will be
executed only if the user has entered any wrong value as his choice i.e. other than
sD
Example program :
al
class Example_switch
{
ri
switch (month)
{
case 1:
Tu
Page 35
case 4:
System.out.println("The month of April");
break;
case 5:
System.out.println("The month of May");
break;
case 6:
System.out.println("The month of June");
m
break;
case 7:
System.out.println("The month of July");
co
break;
case 8:
System.out.println("The month of August");
break;
a.
case 9:
System.out.println("The month of September");
break;
iy
case 10:
System.out.println("The month of October");
break;
case 11:
un
System.out.println("The month of November");
break;
case 12:
sD
}
}
}
ri
Iteration Statements
to
1) while
2) do-while
3) for
while
Syntax:
while(conditions)
{
//Loop body
}
m
{
public static void main (String[ ] args)
{
co
int i =0;
while (i < 4)
{
System.out.println ("i is : " + i);
a.
i++;
}
iy
}
}
do-while
un
It will enter the loop without checking the condition first and checks the condition
after the execution of the statements. That is it will execute the statement once and
then it will evaluate the result according to the condition. Exit controlled
sD
Syntax:
do
{
//Loop body
al
}while(condition);
ri
do {
System.out.println ("i is : " + i);
i++;
} while (i < 4);
}
}
Page 37
6. for
The concept of Iteration has made our life much easier. Repetition of similar tasks is
what Iteration is and that too without making any errors. Until now we have learnt
how to use selection statements to perform repetition.
Syntax:
m
for(initialization;test condition;increment)
{
//Loop body
co
}
public class ForExample
{
public static void main (String[ ] args)
a.
{
for( int i =0;i < 4;i++)
{
iy
System.out.println ("i is : " + i);
}
}
un
}
Jump Statements
Java jump statements enable transfer of control to other parts of program.
sD
In addition, Java supports exception handling that can also alter the control
flow of a program.
ri
Java programs.
Continue Statement in Java is used to skip the part of loop. Unlike break statement it
does not terminate the loop , instead it skips the remaining part of the loop and
control again goes to check the condition again.
Tu
Syntax:
{
//loop body
-----------
-----------
-----------
continue;
Page 38
----------
-----------
}
Continue Statement is Jumping Statement in Java Programming like break.
Continue Statement skips the Loop and Re-Executes Loop with new
condition.
Continue Statement can be used only in Loop Control Statements such
m
as For Loop | While Loop | do-While Loop.
Continue is Keyword in Java Programming.
co
Example:
public class continue_demo {
public static void main(String[] args)
a.
{ int j;
for (j = 1; j < 5; j++)
{ if (j == 3) {
iy
System.out.println("continue!");
continue;
}
un
System.out.println(j);
}
}
}
sD
Out Put:
C:\>java continue_demo
1
al
2
continue!
4
ri
Page 39
Syntax:-
return;
m
There may be a situation when you need to execute a block of code several number
of times. In general, statements are executed sequentially: The first statement in a
co
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
a.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
iy
programming languages:
un
sD
al
ri
true.
For Loop checks the contrition and executes the set of the statements , It is
loop control statement in java.
For Loop contain the following statements such as “Initialization” ,
“Condition” and “Increment/Decrement” statement.
Page 40
m
co
a.
Example : For Loop Statement
iy
un
class ForDemo {
public static void main(String[]
sD
}
}
ri
Output :
Count is: 1
to
Count is: 2
Count is: 3
Count is: 4
Tu
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Page 41
m
termination condition is met.
co
entrance.
If initial condition is true then and then only control enters into the while
a.
loop body
iy
In for loop initialization,condition and increment all three statements are
combined into the one statement , in “while loop” all these statements are
un
written as separate statements.
Conditional Expression written inside while must return boolean value.
sD
al
ri
Syntax :
to
while(condition) {
// body of loop
Tu
Page 42
When condition becomes false, control passes to the next line of code
immediately following the loop.
The curly braces are unnecessary if only a single statement is being repeated.
Example :
class WhileDemo {
m
public static void main(String[]
args){ int cnt = 1;
co
while (cnt < 11) {
System.out.println("Number Count : " + cnt);
count++;
a.
}
}}
iy
Java do-while loop: un
In java “Do-while” is iteration statements like for loop and while loop.
It is also called as “Loop Control Statement“.
“Do-while Statement” is Exit Controlled Loop because condition is check
sD
In do-while loop body gets executed once whatever may be the condition but
condition must be true if you need to execute body for second time.
to
Tu
Page 43
m
co
Syntax : Do-While Loop
a.
do {
iy
Statement1;
Statement2;
Statement3;
un
..
.
sD
StatementN;
} while (expression);
Example 1 : Printing Numbers
al
class DoWhile {
public static void main(String args[])
ri
{ int n = 5;
do
to
{
System.out.println("Sample : " + n);
Tu
n--;
}while(n > 0);
}
Lab Programs:
1. Write a JAVA program to display default value of all primitive data types of JAVA
Page 44
class DefaultValues
{
static byte b;
static short s;
static int i;
m
static long l;
static float f;
co
static double d;
static char c;
a.
static boolean bl;
public static void main(String[] args)
iy
{
System.out.println("Byte :"+b);
un
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
sD
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
al
System.out.println("Boolean :"+bl);
}
ri
}
Out Put:
to
E:\JAVA>javac DefaultValues.java
E:\JAVA>java DefaultValues
Tu
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Page 45
Double :0.0
Char :
Boolean :false
2. Write a JAVA program to get the minimum and maximum value of a primitive data
types
m
public class MinMaxExample
{
public static void main(String[] args)
co
{
System.out.println("Byte.MIN = " + Byte.MIN_VALUE);
a.
System.out.println("Byte.MAX = " + Byte.MAX_VALUE);
System.out.println("Short.MIN = " + Short.MIN_VALUE);
iy
System.out.println("Short.MAX = " + Short.MAX_VALUE);
System.out.println("Integer.MIN = " + Integer.MIN_VALUE);
un
System.out.println("Integer.MAX = " + Integer.MAX_VALUE);
System.out.println("Long.MIN = " + Long.MIN_VALUE);
System.out.println("Long.MAX = " + Long.MAX_VALUE);
sD
}
Out Put:
to
E:\JAVA>javac MinMaxExample.java
E:\JAVA>java MinMaxExample
Tu
Byte.MIN = -128
Byte.MAX = 127
Short.MIN = -32768
Short.MAX = 32767
Integer.MIN = -2147483648
Page 46
Integer.MAX = 2147483647
Long.MIN = -9223372036854775808
Long.MAX = 9223372036854775807
Float.MIN = 1.4E-45
Float.MAX = 3.4028235E38
Double.MIN = 4.9E-324
m
Double.MAX = 1.7976931348623157E308
co
4. Write a JAVA program to display the Fibonacci sequence
a.
class FibonacciExample1{
public static void main(String args[])
iy
{
int n1=0,n2=1,n3,i,count=10;
un
System.out.print(n1+" "+n2);
for(i=2;i<count;++i)
{
sD
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
al
n2=n3;
}
ri
}
}
to
Out Put:
Tu
E:\JAVA>javac FibonacciExample1.java
E:\JAVA>java FibonacciExample1
0 1 1 2 3 5 8 13 21 34
Page 47
m
Out Put: }
E:\JAVA>javac CommandLineExample.java
co
E:\JAVA>java CommandLineExample rise prakasam cse
Your first argument is: rise
a.
Your first argument is: prakasam
Your first argument is: cse
iy
5. Write java Program which is capable of adding any number of integers
passed as command line arguments.
un
public class Add {
{ int sum = 0;
for (int i = 0; i < args.length; i++) {
sum = sum + Integer.parseInt(args[i]);
al
}
System.out.println("The sum of the arguments passed is " + sum);
ri
}
}
to
OutPut:
E:\JAVA>javac Add.java
Tu
E:\JAVA>java Add 1 2 5
The sum of the arguments passed is 8
Page 48
m
co
a.
Classes:
iy
Class is a template for creating objects which defines its state and behavior.
A class contains field and method to define the state and behavior of its object.
un
In Java everything is encapsulated under classes. Class is the core of Java
language.
Class can be defined as a template/ blueprint that describe the behaviors
sD
that operate on that data. The data or variables defined within a class are
called instance variables and the code that operates on this data is known
to
as methods.
A class in java can contain:
Tu
data member
method
constructor
block
class and interface
Page 49
m
java.lang.Object.
It may optionally implement any number of comma-separated interfaces.
co
The class's variables and methods are declared within a set of curly braces {} .
Each .java source file may contain only one public class. A source file may
a.
contain any number of default visible classes.
Finally, the source file name must match the public class name and it must have
iy
a .java suffix.
By convention, class names capitalize the initial of each word.
un
For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator.
This type of naming convention is known as Pascal naming convention.
The other convention, the camel naming convention, capitalize the initial of each
sD
class <class_name>
{
data member;
ri
method;
}
to
Example:
class Student.
{
Tu
String name;
int rollno;
int age;
}
Page 50
Object in Java:
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tengible and
intengible). The example of integible object is banking system.
An object has three characteristics:
m
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object
co
such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique
ID. The value of the ID is not visible to the external user. But,it
a.
is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known
iy
as its state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which
un
objects are created. So object is the instance(result) of a class.
Creatingan Object:
sD
type.
Instantiation: The 'new' key word is used to create the object.
to
Syntax:
Page 51
Here constructor of the class(Class_Name) will get executed and object will be
created(ClassObjectRefrence will hold the reference of created object in memory).
m
classname objectname = new classname();
When a reference is made to a particular student with its property then it becomes
co
an object, physical existence of Student class.
Student std=new Student();
After the above statement std is instance/object of Student class. Here
a.
the new keyword creates an actual physical copy of the object and assign it to
iy
the std variable. It will have physical existence and get memory in heap
In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing
to
Page 52
}
}
Out Put:
E:\JAVA>javac Student1.java
E:\JAVA>java Student1
100
m
500
METHODS IN JAVA:
co
Method describe behavior of an object. A method is a collection of statements
that are group together to perform an operation.
a.
A method is like function i.e. used to expose behavior of an object.
iy
Advantage of Method
Code Reusability
Code Optimization
un
Syntax :
return-type methodName(parameter-list)
{
sD
//body of method
}
al
Example of a Method
public String getName(String st)
ri
{
String name="StudyTonight";
to
name=name+st;
return name;
}
Tu
Page 53
m
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is
co
declare in method heading.
Method name : Actual name of the method.
a.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
iy
Methods define actions that a class's objects (or instances) can do.
A method has a declaration part and a body.
un
The declaration part consists of a return value, the method name, and a list of
arguments.
The body contains code that perform the action.
sD
Example:
ri
public class
MethodExample{ public static
to
void PrintLine() {
System.out.println("This is a line of text.");
Tu
}
public static void main(String[] args)
{ System.out.println("Start Here");
PrintLine();
System.out.println("Back to the Main");
PrintLine();
Page 54
System.o
ut.printl
n("End
Here");
m
co
a.
iy
un
sD
al
ri
to
Tu
Page 55
}
}
Out Put:
E:\JAVA>javac MethodExample.java
E:\JAVA>java MethodExample
Start Here
m
This is a line of text.
Back to the Main
co
This is a line of text.
End Here
a.
Example: Method with arguments:
class Method
iy
{
public static void main(String args[])
{
un
Method obj = new Method();
obj.disp('a');
sD
obj.disp('a',10);
}
public void disp(char c)
al
{
System.out.println(c);
ri
}
public void disp(char c, int num)
to
{
System.out.println(c + " "+num);
Tu
}
}
OutPut:
E:\JAVA>javac Method.java
Page 56
E:\JAVA>java Method
a
a 10
Access Control:
Java provides control over the visibility of variables and methods.
Encapsulation, safely sealing data within the capsule of the class Prevents
programmers from relying on details of class implementation, so you can
m
update without worry
Helps in protecting against accidental or wrong usage.
Keeps code elegant and clean (easier to maintain)
co
Access Modifiers:
Public
a.
Private
Protected
iy
Default
un
Access modifiers help you set the level of access you want for your class,
variables as well as methods.
Access modifiers (Some or All) can be applied on Class, Variable, Methods
Yes No
Package
Public
ri
When set to public, the given class will be accessible to all the classes
available in Java world.
Default
to
When set to default, the given class will be accessible to the classes which are
defined in the same package.
Tu
Default
Public
Protected
Private
Page 57
Note*: Visibility of the class should be checked before checking the visibility of the
variable defined inside that class. If the class is visible only then the variables
defined inside that class will be visible . If the class is not visible then no variable
will be accessible, even if it is set to public.
Default
If a variable is set to default, it will be accessible to the classes which are
defined in the same package. Any method in any class which is defined in the
m
same package can access the variable via Inheritance or Direct access.
Public
co
If a variable is set to public it can be accessible from any class available in the
Java world. Any method in any class can access the given variable via
Inheritance or Direct access.
a.
Protected
If a variable is set to protected inside a class, it will be accessible from its sub
iy
classes defined in the same or different package only via Inheritance.
Private
A variable if defined private will be accessible only from within the class it is
sD
defined. Such variables are not accessible from outside the defined class, not
even its subclass .
Page 58
Default
When a method is set to default it will be accessible to the class which are
defined in the same package. Any method in any class which is defined in the
same package can access the given method via Inheritance or Direct access.
Public
m
When a method is set to public it will be accessible from any class available in
the Java world. Any method in any class can access the given method via
Inheritance or Direct access depending on class level access.
co
Protected
If a method is set to protected inside a class, it will be accessible from its sub
classes defined in the same or different package.
Note:* The only difference between protected and default is that protected
a.
access modifiers respect class subclass relation while default does not.
iy
Private
A method if defined private will be accessible only from within the class it is
defined. Such methods are not accessible from outside the defined class, not
even its subclass.
un
Java Access Modifiers Table for Method
sD
CONSTRUCTORS in java:
Page 59
A constructor is a special member method which will be called by the JVM implicitly
(automatically) for placing user/programmer defined values instead of placing
default values.Constructors are meant for initializing the object.
ADVANTAGES of constructors:
A constructor eliminates placing the default values.
A constructor eliminates calling the normal method implicitly.
m
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
co
Constructor name must be similar to name of the class.
Constructor should not return any value even void also (if we write the
return type for theconstructor then that constructor will be treated as
a.
ordinary method).
Constructors should not be static since constructors will be called each and
iy
every time whenever an object is creating.
Constructor should not be private provided an object of one class is created
un
in another class (constructor can be private provided an object of one class
created in the same class).
sD
TYPES of constructors:
al
Syntax:
class <clsname>
{
clsname () //default constructor
{
Block of statements;
Page 60
………………………………;
………………………………;
}
………………………;
………………………;
};
m
For example:
class Test
co
{
int a, b;
a.
Test ()
{
iy
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
a=10;
un
b=20;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
sD
}
};
class TestDemo
al
{
public static void main (String [] args)
ri
{
Test t1=new Test ();
to
}
};
Tu
OutPut:
E:\JAVA>javac TestDemo.java
E:\JAVA>java TestDemo
I AM FROM DEFAULT CONSTRUCTOR...
VALUE OF a = 10
Page 61
VALUE OF b = 20
RULE-1:
Whenever we create an object only with default constructor, defining the default
constructor is optional. If we are not defining default constructor of a class, then JVM
will call automatically system defined default constructor (SDDC). If we define, JVM
will call user/programmer defined default constructor (UDDC).
m
A parameterized constructor is one which takes some parameters.
Syntax:
co
class <clsname>
{
a.
…………………………;
…………………………;
iy
<clsname> (list of parameters) //parameterized constructor
{
un
Block of statements (s);
}
…………………………;
sD
…………………………;
}
For example:
al
class Test
{
ri
int a, b;
Test (int n1, int n2)
to
{
System.out.println ("I AM FROM PARAMETER CONSTRUCTOR...");
Tu
a=n1;
b=n2;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
Page 62
};
class TestDemo1
{
public static void main (String k [])
{
Test t1=new Test (10, 20);
m
}
};
co
OutPut:
E:\JAVA>javac TestDemo1.java
a.
E:\JAVA>java TestDemo1
I AM FROM PARAMETER CONSTRUCTOR...
iy
VALUE OF a = 10
VALUE OF b = 20
un
RULE-2:
sD
Overloaded constructor:
ri
parameters and order of parameters. Here, at least one thing must be differentiated.
For example:
Tu
m
(overloaded constructors).
co
Example:
class Test
a.
{
int a, b;
iy
Test ()
{
un
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
a=1;
b=2;
sD
a=x;
b=y;
Tu
Page 64
m
}
Test (Test T)
co
{
System.out.println ("I AM FROM OBJECT PARAMETERIZED
a.
CONSTRUCTOR...");
a=T.a;
iy
b=T.b;
System.out.println ("VALUE OF a ="+a);
un
System.out.println ("VALUE OF b ="+b);
}
};
sD
class TestDemo2
{
public static void main (String k [])
al
{
Test t1=new Test ();
ri
};
Output:
E:\JAVA>javac TestDemo2.java
E:\JAVA>java TestDemo2
I AM FROM DEFAULT CONSTRUCTOR...
Page 65
VALUE OF a =1
VALUE OF b =2
I AM FROM DOUBLE PARAMETERIZED CONSTRUCTOR...
VALUE OF a =10
VALUE OF b =20
I AM FROM SINGLE PARAMETERIZED CONSTRUCTOR...
m
VALUE OF a =1000
VALUE OF b =1000
co
I AM FROM OBJECT PARAMETERIZED CONSTRUCTOR...
VALUE OF a =1
a.
VALUE OF b =2
iy
un
‘this ‘:
sD
‘this’ is an internal or implicit object created by JAVA for two purposes. They
are
‘this’ object is internally pointing to current class object.
Page 66
Whenever the formal parameters and data members of the class are similar,
to differentiate the data members of the class from formal parameters, the
data members of class must be proceeded by ‘this’.
this (): this () is used for calling current class default constructor from
current class parameterized constructors.
this (…): this (…) is used for calling current class parameterized constructor
m
from other category constructors of the same class.
co
Usage of java this keyword
1) The this keyword can be used to refer current class instance variable.
a.
2) this() can be used to invoked current class constructor.
iy
Rule for ‘this’:
Whenever we use either this () or this (…) in the current class constructors,
un
that statements must be used as first statement only.
The order of the output containing this () or this (...) will be in the reverse
order of the input which we gave as inputs.
sD
al
NOTE:
ri
Whenever we refer the data members which are similar to formal parameters, the
JVM gives first preference to formal parameters whereas whenever we write a
to
keyword this before the variable name of a class then the JVM refers to data
members of the class. this methods are used for calling current class constructors.
NOTE:
Tu
• If any method called by an object then that object is known as source object.
• If we pass an object as a parameter to the method then that object is known as
target object.
Examples:
Page 67
1) The this keyword can be used to refer current class instance variable.
class
Student{ int
id;
int marks;
m
marks){ this.id = id;
this.marks = marks;
}
co
void display(){System.out.println(id+" "+marks);}
public static void main(String args[]){
Student s1 = new Student(111,1500);
Student s2 = new Student(222,2000);
a.
s1.display();
s2.display();
}
iy
}
Out Put:
E:\JAVA>javac Student.java
un
E:\JAVA>java Student
111 1500
222 2000
sD
class
Student{ int
al
id;
int marks;
ri
Student()
{System.out.println("default constructor is invoked");}
to
this.id = id;
this.marks = marks;
}
void display(){System.out.println(id+" "+marks);}
public static void main(String args[]){
Student s1 = new Student(111,1500);
Student s2 = new Student(222,2000);
s1.display();
Page 68
s2.display();
m
co
a.
iy
un
sD
al
ri
to
Tu
Page 69
}
}
Out Put:
E:\JAVA>javac Student.java
E:\JAVA>java Student
default constructor is invoked
default constructor is invoked
m
111 1500
222 2000
co
Java static keyword
The static keyword in java is used for memory management mainly. We can apply
java static keyword with variables, methods, blocks and nested class. The static
a.
keyword belongs to the class than instance of the class.
iy
The static can be:
The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,college
al
Page 70
get memory each time when object is created.All student have its unique rollno and
m
co
a.
iy
un
sD
al
ri
to
Tu
Page 71
name so instance data member is good.Here, college refers to the common property
of all objects.If we make it static,this field will get memory only once.
Example of static variable
class
Student8{ int
rollno; String
m
name;
static String college ="RISE";
co
Student8(int r,String
n){ rollno = r;
name = n;
a.
}
void display (){System.out.println(rollno+" "+name+" "+college);}
iy
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
un
s1.display();
s2.display();
}
sD
}
Output:111 Karan RISE
222 Aryan RISE
al
If you apply static keyword with any method, it is known as static method.
to
static method can access static data member and can change the value of it.
Page 72
m
co
a.
iy
un
sD
al
ri
to
Tu
Page 73
static void
change(){ college =
"RPRA";
}
Student9(int r, String
n){ rollno = r;
m
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
co
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
a.
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
iy
s1.display();
s2.display();
s3.display();
un
}
}
Output:111 Karan RPRA
sD
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static
ri
method directly.
this cannot be used in static context.
to
ARRAYS
Arrays are generally effective means of storing groups of variables. An array is a
Tu
group of variables that share the same name and are ordered sequentially from zero
to one less than the number of variables in the array. The number of variables that
can be stored in an array is called the array's dimension. Each variable in the array
is called an element of the array.
Creating Arrays:
There are three steps to creating an array, declaring it, allocating it and initializing it.
Page 74
Declaring Arrays:
Like other variables in Java, an array must have a specific type like byte, int,
String or double. Only variables of the appropriate type can be stored in an array.
You cannot have an array that will store both ints and Strings, for instance.
Like all other variables in Java an array must be declared. When you declare
m
an array variable you suffix the type with [] to indicate that this variable is an array.
Here are some examples:
int[] k;
co
float[] yt;
String[] names;
In other words you declare an array like you'd declare any other variable except you
a.
append brackets to the end of the variable type.
Allocating Arrays
iy
Declaring an array merely says what it is. It does not create the array. To actually
create the array (or any other object) use the new operator. When we create an
un
array we need to tell the compiler how many elements will be stored in it. Here's
how we'd create the variables declared above: new
k = new int[3];
yt = new float[7];
sD
Initializing Arrays
ri
Individual elements of the array are referenced by the array name and by an integer
which represents their position in the array. The numbers we use to identify them
are called subscripts or indexes into the array. Subscripts are consecutive integers
to
beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we
started counting at zero there is no k[3], and trying to access it will generate an
Tu
Page 75
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";
This step is called initializing the array or, more precisely, initializing the elements
of the array. Sometimes the phrase "initializing the array" would be reserved for
when we initialize all the elements of the array.For even medium sized arrays, it's
unwieldy to specify each element individually. It is often helpful to use for loops to
m
initialize the array. For instance here is a loop that fills an array with the squares of
the numbers from 0 to 100.
float[] squares = new float[101];
co
for (int i=0; i <= 500; i++)
{ squares[i] = i*2;
a.
}
iy
Declaring, Allocating and Initializing Two Dimensional Arrays
Two dimensional arrays are declared, allocated and initialized much like one
un
dimensional arrays. However we have to specify two dimensions rather than one,
and we typically use two nested for loops to fill the array. for The array examples
above are filled with the sum of their row and column indices. Here's some code that
would create and fill such an array:
sD
class FillArray {
al
{ int[][] M;
M = new int[4][5];
to
{ M[row][col] = row+col;
}
}
}
}
Page 76
Multidimensional Arrays
You don't have to stop with two dimensional arrays. Java lets you have arrays of
m
three, four or more dimensions. However chances are pretty good that if you need
more than three dimensions in an array, you're probably using the wrong data
structure. Even three dimensional arrays are exceptionally rare outside of scientific
co
and engineering applications.
The syntax for three dimensional arrays is a direct extension of that for two-
dimensional arrays. Here's a program that declares, allocates and initializes a three-
a.
dimensional array:
class Fill3DArray {
iy
public static void main (String args[])
un
{ int[][][] M;
M = new int[4][5][3];
}
}
ri
}
}
Strings
to
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write:
String greeting = "Hello world!";
In this case, "Hello world!" is a string literal—a series of characters in your code that
is enclosed in double quotes. Whenever it encounters a string literal in your code,
the compiler creates a String object with its value—in this case, Hello world!.
Page 77
As with any other object, you can create String objects by using the new keyword
and a constructor. The String class has thirteen constructors that allow you to
provide the initial value of the string using different sources, such as an array of
characters:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println(helloString);
m
The last line of this code snippet displays hello.
String Length
co
Methods used to obtain information about an object are known as accessor methods.
One accessor method that you can use with strings is the length() method, which
returns the number of characters contained in the string object. After the following
a.
two lines of code have been executed, len equals 17:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
iy
A palindrome is a word or sentence that is symmetric—it is spelled the same
forward and backward, ignoring case and punctuation. Here is a short and
un
inefficient program to reverse a palindrome string. It invokes the String method
charAt(i), which returns the ith character in the string, counting from 0.
}
Tu
Page 78
}
Running the program produces this output:
doT saw I was toD
To accomplish the string reversal, the program had to convert the string to an array
of characters (first for loop), reverse the array into a second array (second for loop),
and then convert back to a string. The String class includes a method, getChars(), to
convert a string, or a portion of a string, into an array of characters so we could
m
replace the first for loop in the program above with
palindrome.getChars(0, len, tempCharArray, 0);
co
Concatenating Strings
The String class includes a method for concatenating two strings:
string1.concat(string2);
a.
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");
iy
Strings are more commonly concatenated with the + operator, as in
"Hello," + " world" + "!"
which results in
un
"Hello, world!"
The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
sD
different values. You can pass N (1,2,3 and so on) numbers of arguments
from the command prompt.
Page 79
m
Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line.
For this purpose, we have traversed the array using for loop.
co
class A{
public static void main(String
args[]){ for(int i=0;i<args.length;i++)
a.
System.out.println(args[i]);
}
}
iy
OutPut:
D:\>javac A.java
un
D:\>java A 1 2 3 Rise Cse
1
2
3
sD
Rise
Cse
al
ri
to
Tu
Page 80
UNIT – III
INHERITANCE
m
METHOD OVERLAODING
SUPER KEYWORD
co
FINAL KEYWORD
ABSTRACT CLASS
a.
INTERFACES
PACKAGES
iy
CREATING PACKAGES
un
USING PACKAGES
ACCESS PROTECTION
JAVA.LANG.PACKAGE
sD
EXCEPTIONS
al
ASSERTIONS
Tu
Page 1
INHERITANCE IN JAVA
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
m
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.
co
Inheritance represents the IS-A relationship, also known as parent-child relationship.
a.
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
iy
4. }
The extends keyword indicates that you are making a new class that derives from an existing
un
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
sD
called a subclass.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
ri
In java programming, multiple and hybrid inheritance is supported through interface only.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Page 2
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
m
error now.
1. class A{
co
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
a.
6. }
7. class C extends A,B{//suppose if it were
8.
iy
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
un
13. }
Test it Now
sD
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
ri
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
to
Page 3
In java, Method Overloading is not possible by changing the return type of the
method.
m
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
co
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
a.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
iy
3. super is used to invoke immediate parent class method.
un
FINAL KEYWORD IN JAVA
The final keyword in java is used to restrict the user. The java final keyword can be used in
sD
1. variable
2. method
al
3. class
ri
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable.
to
It can be initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only.
Tu
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Page 4
m
If you make any class as final, you cannot extend it.
co
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
a.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
iy
Example abstract class
abstract class A {}
un
Abstract method
sD
A method that is declared as abstract and does not have implementation is known as abstract
method.
In this example, Bike the abstract class that contains only one abstract method run. It
to
11. {
12. Bike obj = new Honda4();
13. obj.run();
14. }
15. }
Test it Now
running safely..
m
Another example of abstract class in java:
co
File: TestBank.java
1. abstract class Bank
2. {
a.
3. abstract int getRateOfInterest();
4. }
5. class SBI extends Bank
iy
6. {
7. int getRateOfInterest(){return 7;}
8. }
un
9. class PNB extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12.
sD
Test it Now
to
INTERFACE IN JAVA
Tu
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritances in Java.
Page 6
m
There are mainly three reasons to use interface. They are given below.
co
By interface, we can support the functionality of multiple inheritance.
NOTE: Interface fields are public, static and final by default, and methods
are public and abstract.
a.
Understanding relationship between classes and interfaces
iy
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
un
sD
al
ri
In this example, Printable interface have only one method, its implementation
is provided in the A class.
Tu
1. interface printable {
2. void print();
3. }
4. class A6 implements printable {
5. public void print()
6. {
Page 7
7. System.out.println("Hello");
8. }
9. public static void main(String args[]){
10. A6 obj = new A6();
11. obj.print();
12. }
13. }
m
Test it Now
co
Output:Hello
a.
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
iy
as multiple inheritance.
un
sD
al
1. interface Printable{
2. void print();
ri
3. }
4.
5. interface Showable{
to
6. void show();
7. }
8.
Tu
9. class A7 implements
Printable,Showable{ 10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
15. A7 obj = new A7();
16. obj.print();
Page 8
17. obj.show();
18. }
19. }
Test it Now
m
Output: Hello
Welcome
co
Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example:
a.
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
iy
1. //How Serializable interface is written?
2. public interface Serializable
3. {
4.
un
5. }
sD
An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter.
al
For example:
1. interface printable{
ri
2. void print();
3. interface MessagePrintable
4. {
to
5. void msg();
6. }
7. }
Tu
Page 9
JAVA PACKAGE
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.
m
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.
co
Advantage of Java Package
a.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
iy
2) Java package provides access protection.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
al
7. }
If you are not using any IDE, you need to follow the syntax given below:
Tu
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
Page 10
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
m
To Run: java mypack.Simple
co
Output:Welcome to package
a.
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.
iy
How to access package from another package?
un
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
sD
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
al
The import keyword is used to make the classes and interface of another package accessible to
the current package.
ri
1. //save by A.java
2. package pack;
3. public class A{
Tu
Page 11
Output: Hello
m
2) Using packagename.classname
co
If you import package.classname then only declared class of this package will be accessible.
a.
2.
3. package pack;
iy
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
un
2.
3. package mypack;
4. import pack.A;
5.
sD
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
al
10. }
11. }
Output: Hello
ri
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
Tu
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Page 12
m
1. //save by B.java
co
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
a.
6. pack.A obj = new pack.A();//using fully qualified name
7. obj.msg();
8. }
iy
9. }
Output:Hello
un
EXCEPTION HANDLING IN JAVA
sD
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
al
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object
to
Page 13
m
1. statement 1;
2. statement 2;
co
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
a.
7. statement 7;
8. statement 8;
9. statement 9;
iy
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5,
un
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the exception will be executed. That is why we use exception handling in java.
sD
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
al
1. Checked Exception
2. Unchecked Exception
ri
3. Error
to
1) Checked Exception
Tu
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
Page 14
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
m
3) Error
co
Common scenarios where exceptions may occur
a.
There are given some scenarios where unchecked exceptions can occur. They are as follows:
iy
If we divide any number by zero, there occurs an ArithmeticException.
1.
un
int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
al
1. String s=null;
2. System.out.println(s.length());//NullPointerException
ri
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
Tu
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Page 15
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
m
Java Exception Handling Keywords
co
There are 5 keywords used in java exception handling.
1. try
a.
2. catch
3. finally
iy
4. throw
5. throws un
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
sD
1. try{
2. //code that may throw exception
3. }
ri
4. catch(Exception_class_Name ref){}
to
4. finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
Page 16
EXAMPLE:
m
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
co
7. }
8. }
Test it Now
a.
Output:
iy
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code... un
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
al
EXAMPLE:
to
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
Page 17
11. }
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
m
Java throw keyword
co
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
a.
keyword is mainly used to throw custom exception.
iy
The syntax of java throw keyword is given below.
throw exception;
un
java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If
sD
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
5. else
6. System.out.println("welcome to vote");
7. }
to
12. }
Test it Now
Output:
Page 18
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
m
Syntax of java throws
1. return_type method_name() throws
exception_class_name{ 2. ...
co
3. }
a.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
iy
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
un
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
sD
8. }
9. void p(){
10. try{
11. n();
al
18. }
19. }
Tu
Test it Now
Output:
exception handled
normal flow...
Page 19
In exception enrichment you do not wrap exceptions. Instead you add contextual information
to the original exception and rethrow it. Rethrowing an exception does not reset the stack trace
embedded in the exception.
m
Here is an example:
co
public void method2() throws
EnrichableException{ try{
a.
method1();
iy
} catch(EnrichableException e){
}
sD
ASSERTION:
Assertion is a statement in java. It can be used to test your assumptions about the program.
Tu
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
Page 20
1. assert expression;
m
1. assert expression1 : expression2;
co
Simple Example of Assertion in java:
1. import java.util.Scanner;
a.
2.
3. class AssertionExample{
4. public static void main( String
iy
args[] ){ 5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
un
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
sD
13. }
14. }
al
ri
to
Tu
Page 21
UNIT -IV
Multithreading
m
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
co
But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching
a.
between the threads takes less time than process.
iy
Advantage of Java Multithreading
un
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
sD
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
al
Multitasking
ri
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
Tu
o Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
m
What is Thread in java
co
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
a.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
iy
un
sD
al
ri
to
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)z
5. Terminated
m
co
a.
iy
un
sD
al
ri
to
1) New
Tu
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
m
5) Terminated
co
A thread is in terminated or dead state when its run() method exits.
a.
There are two ways to create a thread:
iy
1. By extending Thread class
2. By implementing Runnable interface.
un
How to create thread
Thread class:
al
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
ri
Thread()
Thread(String name)
Tu
Thread(Runnable r)
Thread(Runnable r,String name)
on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
m
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
co
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
a.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
iy
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
un
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
sD
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
al
22. public static boolean interrupted(): tests if the current thread has been
interrupted.
ri
Runnable interface:
to
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
Tu
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
m
1) By extending Thread class:
1. class Multi extends Thread{
co
2. public void run(){
3. System.out.println("thread is running...");
4. }
a.
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
iy
8. }
9. }
Output:thread is running...
un
Who makes your class object as thread object?
sD
Thread class constructor allocates a new thread object.When you create object of
Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread
class constructor is invoked(by super() as first statement).So your Multi class object is
thread object now.
al
ri
If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitely create Thread class object.We are passing the
object of your class that implements Runnable so that your class run() method may
execute.
m
Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority
co
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
a.
3 constants defiend in Thread class:
iy
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
un
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
sD
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
Tu
m
Joining threads
co
Sometimes one thread needs to know when another thread is ending. In java,
isAlive() and join() are two different methods to check whether a thread has finished its
execution.
a.
The isAlive() methods return true if the thread upon which it is called is still running
otherwise it return false.
iy
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the
un
thread on which it is called terminates.
final void join() throws InterruptedException
sD
Using join() method, we tell our thread to wait until the specifid thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.
final void join(long milliseconds) throwsInterruptedException
al
ri
{
Tu
System.out.println("r1 ");
try{ Thread.sleep(5
00);
}catch(InterruptedException ie){}
m
System.out.println("r2 ");
co
}
a.
{
iy
MyThread t1=new MyThread();
t2.start();
sD
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
al
}
ri
}
to
Output
r1
Tu
true
true
r1
r2
r2
m
public void run()
{
co
System.out.println("r1 ");
try{
a.
Thread.sleep(500);
}catch(InterruptedException ie){}
iy
System.out.println("r2 ");
}
un
public static void main(String[] args)
{
sD
t2.start();
ri
}
}
to
Output
r1
Tu
r1
r2
r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing
"r1" on console thread t1 goes to sleep for 500 mls.At the same time Thread t2 will start its
process and print "r1" on console and then goes into sleep for 500 mls. Thread t1 will wake
up from sleep and print "r2" on console similarly thread t2 will wake up from sleep and
print "r2" on console. So you will get output like r1 r1 r2 r2
m
Example of thread with join() method
co
{
public void run()
{
a.
System.out.println("r1 ");
iy
try{
Thread.sleep(500);
}catch(InterruptedException ie){}
un
System.out.println("r2 ");
sD
}
public static void main(String[] args)
{
al
try{
Tu
t2.start();
}
Output
r1
r2
r1
m
r2
In this above program join() method on thread t1 ensure that t1 finishes it process before
co
thread t2 starts.
a.
Specifying time with join()
iy
If in the above program, we specify time while using join() with m1, then m1 will execute
for that time, and thenm2 and m3 will join it.
m1.join(1500);
un
Doing so, initially m1 will execute for 1.5 seconds, after which m2 and m3 will join it.
In the last chapter we have seen the ways of naming thread in java. In this chapter we will
sD
1. Logically we can say that threads run simultaneously but practically its not true,
ri
only one Thread can run at a time in such a ways that user feels that concurrent
environment.
to
2. Fixed priority scheduling algorithm is used to select one thread for execution based
on priority.
Tu
package com.c4learn.thread;
m
public static void main(String[] args)
co
throws InterruptedException {
a.
ThreadPriority t1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
iy
t1.start();
un
t2.start();
}
sD
Output :
al
5
ri
Each thread has normal priority at the time of creation. We can change or modify the
thread priority in the following example 2.
Tu
Example#2: SettingPriority
package com.c4learn.thread;
m
System.out.println(tName + " has priority " + tPrio);
co
}
a.
public static void main(String[] args)
throws InterruptedException {
iy
ThreadPriority t0 = new ThreadPriority();
un
ThreadPriority t1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
sD
t1.setPriority(Thread.MAX_PRIORITY);
t0.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
al
ri
t0.start();
t1.start();
to
t2.start();
Tu
}
}
Output :
m
1. We can modify the thread priority using the setPriority() method.
co
3. Java Thread class defines following constants –
4. At a time many thread can be ready for execution but the thread with highest
a.
priority is selected for execution
5. Thread have default priority equal to 5.
iy
Thread:PriorityandConstant un
Thread Priority Constant
MIN_PRIORITY 1
sD
MAX_PRIORITY 10
al
NORM_PRIORITY 5
ri
JavaThreadSynchronization:
to
shared resource then their should be some mechanism to ensure that the resource
Tu
problem.
4. Thread Synchronization is achieved through keyword synchronized.
Typesof Synchronization:
m
co
a.
iy
un
sD
al
ri
Synchronization in Java
to
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Tu
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
m
Types of Synchronization
co
There are two types of synchronization
a.
1. Process Synchronization
2. Thread Synchronization
iy
Here, we will discuss only thread synchronization.
un
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
sD
communication.
1. Mutual Exclusive
1. Synchronized method.
al
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
ri
to
Mutual Exclusive
Tu
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
m
to an object's fields has to acquire the object's lock before accessing them, and then release
the lock when it's done with them.
co
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
a.
Understanding the problem without Synchronization
iy
example: un
1. Class
Table{ 2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
sD
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
al
10.
11. }
12. }
ri
13.
14. class MyThread1 extends Thread{
15. Table t;
to
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
m
34. class TestSynchronization1{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
co
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
a.
41. }
42. }
Output: 5
iy
100
10
200
un
15
300
20
sD
400
25
500
al
ri
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
m
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
co
16. MyThread1(Table t){
17. this.t=t;
18. }
a.
19. public void run(){
20. t.printTable(5);
21. }
iy
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
un
26. MyThread2(Table t){
27. this.t=t;
28. }
sD
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
al
40. t2.start();
41. }
42. }
Tu
Output: 5
10
15
20
25
100
200
300
400
500
m
Example of synchronized method by using annonymous class
co
In this program, we have created the two threads by annonymous class, so less coding is
required.
a.
2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
iy
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
un
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
sD
12. }
13.
14. public class TestSynchronization3{
15. public static void main(String args[]){
al
22. };
23. Thread t2=new Thread(){
24. public void run(){
Tu
25. obj.printTable(100);
26. }
27. };
28.
29. t1.start();
30. t2.start();
31. }
32. }
Output: 5
10
15
20
25
100
m
200
300
400
co
500
a.
Synchronized block in java
Synchronized block can be used to perform synchronization on any specific resource of the
iy
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
un
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
sD
synchronized method.
1. class
Table{ 2.
m
10. }
11. }
12. }//end of the method
13. }
co
14.
15. class MyThread1 extends Thread{
16. Table t;
a.
17. MyThread1(Table t){
18. this.t=t;
19. }
iy
20. public void run(){
21. t.printTable(5);
22. }
23.
un
24. }
25. class MyThread2 extends Thread{
26. Table t;
sD
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
al
32. }
33. }
34.
ri
41. t2.start();
42. }
43. }
Output:5
10
15
20
25
100
200
300
400
500
m
co
Same Example of synchronized block by using annonymous class:
//Program of synchronized block by using annonymous class
1. class
a.
Table{ 2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
iy
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
un
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
sD
22. }
23. };
24. Thread t2=new Thread(){
Tu
33. }
Output:5
10
15
20
25
m
100
200
300
co
400
500
a.
Static synchronization
iy
If you make any static method as synchronized, the lock will be on the class not on object.
un
sD
al
ri
to
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In
case of synchronized method and synchronized block there cannot be interference
between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have
a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock.I want no interference between t1 and
t3 or t2 and t4.Static synchronization solves this problem.
In this example we are applying synchronized keyword on the static method to perform
static synchronization.
1. class
Table{ 2.
m
3. synchronized static void printTable(int
n){ 4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
co
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
a.
10. }
11. }
12.
iy
13. class MyThread1 extends Thread{
14. public void run(){
15. Table.printTable(1);
un
16. }
17. }
18.
19. class MyThread2 extends Thread{
sD
24.
25. class MyThread3 extends Thread{
26. public void run(){
ri
27. Table.printTable(100);
28. }
29. }
to
33. }
34. }
35.
36. public class TestSynchronization4{
37. public static void main(String t[]){
38. MyThread1 t1=new MyThread1();
39. MyThread2 t2=new MyThread2();
40. MyThread3 t3=new MyThread3();
m
Output: 1
2
3
co
4
5
6
a.
7
8
iy
9
10
10
un
20
30
40
sD
50
60
70
80
al
90
100
ri
100
200
to
300
400
500
Tu
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
m
8000
9000
10000
co
a.
Same example of static synchronization by annonymous class
iy
1. class
Table{ 2.
3.
un
synchronized static void printTable(int
n){ 4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
sD
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
al
11. }
12.
13. public class TestSynchronization5 {
ri
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
m
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
co
39. t1.start();
40. t2.start();
41. t3.start();
a.
42. t4.start();
43.
44. }
iy
45. }
Output: 1
2
un
3
4
5
sD
6
7
8
9
al
10
10
ri
20
30
to
40
50
60
Tu
70
80
90
100
100
200
300
400
500
600
700
800
m
900
1000
1000
co
2000
3000
4000
a.
5000
6000
iy
7000
8000
9000
un
10000
sD
The block synchronizes on the lock of the object denoted by the reference .class name
al
4. }
5. }
Introduction to Suspend Resume Thread
Tu
When the sleep() method time is over, the thread becomes implicitly
active. sleep() method is preferable when the inactive time is known earlier. Sometimes,
the inactive time or blocked time may not be known to the programmer earlier; to come to
the task here comes suspend()method. The suspended thread will be in blocked state
until resume() method is called on it. These methods are deprecated, as when not used
with precautions, the thread locks, if held, are kept in inconsistent state or may lead to
deadlocks.
Note: You must have noticed, in the earlier sleep() method, that the thread in blocked state
retains all its state. That is, attribute values remains unchanged by the time it comes into
runnable state.
Suspend Resume Thread: Program explaining the usage of suspend() and resume()
m
methods
co
1 public class SRDemo extends Thread
2 {
a.
3 public static void main( String args[ ] )
4 {
iy
5 SRDemo srd1 = new SRDemo();
9 srd1.start();
10 srd2.start();
al
11 try
ri
12 {
13 Thread.sleep( 1000 );
to
14 srd1.suspend();
16 Thread.sleep( 1000 );
17 srd1.resume();
19
20 Thread.sleep(1000);
21 srd2.suspend();
m
23 Thread.sleep(1000);
24 srd2.resume();
co
25 System.out.println("Resuming thread Second");
26 }
a.
27 catch(InterruptedException e)
iy
28 {
29 e.printStackTrace();
un
30 }
31 }
sD
33 {
34 try
al
35 {
ri
37 {
to
38 Thread.sleep(500);
Tu
40 }
41 }
42 catch(InterruptedException e)
43 {
44 e.printStackTrace();
45 }
46 }
m
47 }
co
a.
iy
un
sD
al
Observe the screenshot, when no thread is suspended both threads are under execution.
WhenFirst thread goes into suspended state, the Second thread goes into action. Similarly,
to
wait()
notify()
notifyAll()
1) wait() method
m
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
co
elapsed.
The current thread must own this object's monitor, so it must be called from the
a.
synchronized method only otherwise it will throw exception.
iy
Method Description
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
al
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:
ri
3) notifyAll() method
Tu
Wakes up all threads that are waiting on this object's monitor. Syntax:
m
co
a.
The point to point explanation of the above diagram is as follows:
iy
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
un
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise
it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
sD
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
ri
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
m
notifyAll() methods completed.
co
Example of inter thread communication in java
a.
1. class Customer{
2. int amount=10000;
iy
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
un
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
sD
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
al
20. }
21. }
22.
23. class Test{
Tu
31. }.start();
32.
33. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
m
deposit completed...
withdraw completed
co
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous
a.
flow of data. Streams are clean way to deal with input/output without having every part of
your code understand the physical.
iy
Java encapsulates Stream under java.io package. Java defines two types of streams. They
are,
un
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and outputof
sD
Byte stream is defined by using two abstract class at the top of hierarchy, they are
ri
These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.
m
Stream class Description
co
BufferedInputStream Used for Buffered Input Stream.
a.
BufferedOutputStream Used for Buffered Output Stream.
iy
DataInputStream Contains method for reading java standard datatype
DataOutputStream
un
An output stream that contain method for writing java standard data
type
sD
These classes define several key methods. Two most important are
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
m
co
a.
iy
These two abstract classes have several concrete classes that handle unicode character.
un
Some important Charcter stream classes.
sD
m
Reader Abstract class that define character stream input
co
Writer Abstract class that define character stream output
a.
Reading Console Input
iy
We use the object of BufferedReader class to take inputs from the keyboard.
un
sD
al
ri
to
Reading Characters
Tu
read() method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(newInputstreamReader(System.in));
char c = (char)br.read(); //Reading character
m
}
}
co
a.
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
iy
String readLine() throws IOException un
Program to take String input from Keyboard in Java
import java.io.*;
sD
class MyInput
{
public static void main(String[] args)
al
{
ri
String text;
InputStreamReader isr = new InputStreamReader(System.in);
to
System.out.println(text);
}
}
m
{
try
co
{
File fl = new File("d:/myfile.txt");
a.
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
iy
while ((str=br.readLine())!=null)
{
un
System.out.println(str);
}
sD
br.close();
fl.close();
}
al
catch (IOException e)
{ e.printStackTrace(); }
ri
}
}
to
Tu
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
m
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
co
fw.close();
fl.close();
a.
}
catch (IOException e)
iy
{ e.printStackTrace(); }
}
un
}
sD
al
ri
to
Tu
UNIT-5
Daemon Threads:
m
service request. When the only remaining threads in a process are daemon threads,
the interpreter exits. This makes sense because when only daemon threads remain,
there is no other thread for which a daemon thread can provide a service.
co
To specify that a thread is a daemon thread, call the setDaemon method with the
argument true. To determine if a thread is a daemon thread, use the accessor
method isDaemon.
a.
Concepts of Applets
Applets are small applications that are accessed on an Internet server, transported
iy
over the Internet, automatically installed, and run as part of a Webdocument.
After an applet arrives on the client, it has limited access to resources, so that it can
un
produce an arbitrary multimedia user interface and run complex computations
without introducing the risk of viruses or breaching data integrity.
applets – Java program that runs within a Java-enabled browser, invoked through a
―applet‖ reference on a web page, dynamically downloaded to the client computer
import java.awt.*;
sD
import java.applet.*;
public class SimpleApplet extends Applet
{ public void paint(Graphics g)
{ g.drawString("A Simple Applet", 20, 20);
al
}
}
ri
NetscapeNavigator.
2. Using an applet viewer, such as the standard JDK tool, appletviewer.
An appletviewer executes your applet in a window. This is generally the fastest and
easiest way to test an applet.
Tu
To execute an applet in a Web browser, you need to write a short HTML text file that
contains the appropriate APPLET tag.
m
computer language.
An applet is an application designed to be transmitted over the Internet and
executed by a Java-compatible Web browser.
co
An applet is actually a tiny Java program, dynamically downloaded across the
network, just like an image, sound file, or video clip.
a.
The important difference is that an applet is an intelligent program, not just an
animation or media file(i.e an applet is a program that can react to user input and
dynamically change—not just run the same animation or sound over and over
iy
Applications require main method to execute.
2. start( )
3. paint( )
ri
4. stop( )
5.destroy( )
When an applet begins, the AWT calls the following methods, in this
to
sequence:
init( )
Tu
start( )
paint( )
When an applet is terminated, the following sequence of method calls takes
place:
stop( )
destroy( )
m
co
a.
iy
init( ): The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run
time of your applet.
un
start( ): The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped. Whereas init( ) is called once—the first
time an applet is loaded—start( ) is called each time an applet's HTML
document is displayed onscreen. So, if a user leaves a web page and comes
sD
paint( ) method has one parameter of type Graphics. This parameter will
contain the graphics context, which describes the graphics environment in
which the applet is running. This context is used whenever output to the
ri
applet is required.
to
stop( ): The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example.
When stop( ) is called, the applet is probably running. Applet uses stop( ) to
Tu
suspend threads that don't need to run when the applet is not visible. To
restart start( ) is called if the user returns to the page.
destroy( ): The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from memory.
The stop( ) method is always called before destroy( ).
Needed if you do any drawing or painting other than just using standard GUI
Components
Any painting you want to do should be done here, or in a method you call
from here
Painting that you do in other methods may or may not happenNever call
m
paint(Graphics), call repaint( )
repaint( ):
Call repaint( ) when you have changed something and want your changes to show
co
up on the screen
You do not need to call repaint() when something in Java’s own components
(Buttons, TextFields, etc.)
a.
You do need to call repaint() after drawing commands (drawRect(...), fillRect(...),
drawString(...), etc.)
repaint( ) is a request--it might not happen
iy
When you call repaint( ), Java schedules a call to update(Graphics g)
update( )
un
When you call repaint( ), Java schedules a call to update(Graphics g)
Here's what update does:
public void update(Graphics g) {
// Fills applet with background color, then
sD
paint(g);
}
Simple example of Applet by appletviewer tool:
al
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.
ri
//First.java
import java.applet.Applet;
to
import java.awt.Graphics;
public class First extends Applet{
Tu
}
/*
<applet code="First.class" width="300" height="300">
</applet> */
c:\>javac First.java
c:\>appletviewer First.java
m
java.awt.Graphics class provides many methods for graphics programming.
co
public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
public void drawRect(int x, int y, int width, int height): draws a rectanglewith
a.
the specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
iy
public abstract void drawOval(int x, int y, int width, int height): is used todraw
oval with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
un
with the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y,ImageObserver
sD
observer): is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, intstartAngle, int
arcAngle): is used to fill a circular or elliptical arc.
al
public abstract void setColor(Color c): is used to set the graphics current colorto
the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to
ri
import java.applet.Applet;
import java.awt.*;
Tu
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
m
}
}
myapplet.html
co
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
a.
</applet>
</body>
</html>
iy
Two Types of Applets:
It is important to state at the outset that there are two varieties of applets. The first
are those based directly on the Applet class described in this chapter. These applets
un
use the Abstract Window Toolkit (AWT) to provide the graphic user interface (or
use no GUI at all). This style of applet has been available since Java was first created.
The second type of applets are those based on the Swing class JApplet. Swing
applets use the Swing classes to provide the GUI. Swing offers a richer and often
sD
easier-to-use user interface than does the AWT. Thus, Swing-based applets arenow
the most popular. However, traditional AWT-based applets are still used, especially
when only a very simple user interface is required.
Because JApplet inherits Applet, all the features of Applet are also available in
JApplet, and most of the information in this chapter applies to both types of applets.
Therefore, even if you are interested in only Swing applets, the information in this
ri
chapter is still relevant and necessary. Understand, however, that when creating
Swing-based applets, some additional constraints apply and these are described
to
Event handling
For the user to interact with a GUI, the underlying operating system must support
Tu
event handling.
Operating systems constantly monitor events such as keystrokes, mouse clicks,
voice command, etc.
operating systems sort out these events and report them to the appropriate
application programs each application program then decides what to do inresponse
to these events
Events
An event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the elements ina
graphical user interface.
Some of the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and clickingthe
m
mouse.
Events may also occur that are not directly caused by interactions with auser
interface.
co
For example, an event may be generated when a timer expires, a counter exceeds a
value, a software or hardware failure occurs, or an operation is completed.
Events can be defined as needed and appropriate by application.
a.
Event sources
A source is an object that generates an event.
This occurs when the internal state of that object changes in some way.
iy
Sources may generate more than one type of event.
source must register listeners in order for the listeners to receive notifications
about a specific type of event.
un
Each type of event has its own registration method.
General form is:
public void addTypeListener(TypeListener el)
sD
Here, Type is the name of the event and el is a reference to the event listener.
For example,
The method that registers a keyboard event listener iscalled
addKeyListener ().
al
Some sources may allow only one listener to register. The general form is:
public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException
Tu
Here Type is the name of the event and el is a reference to the event listener.
When such an event occurs, the registered listener is notified. This is knownas
unicasting the event.
A source must also provide a method that allows a listener to unregister an interest
in a specific type of event.
The general form is:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
For example, to remove a keyboard listener, you would call removeKeyListener( ).
The methods that add or remove listeners are provided by the source that
generates events.
For example, the Component class provides methods to add and removekeyboard
and mouse event listeners.
m
Event classes
The Event classes that represent events are at the core of Java's eventhandling
mechanism.
co
Super class of the Java event class hierarchy is EventObject, which is in java.util.for
all events.
Constructor is :
a.
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ).
iy
The getSource( ) method returns the source of the event. General form is:
Object getSource( )
The toString( ) returns the string equivalent of the event.
un
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are handled by thedelegation
event model.
sD
The package java.awt.event defines several types of events that are generatedby
various user interface elements.
Event Classes in java.awt.event
ActionEvent: Generated when a button is pressed, a list item is double clicked,or
al
becomes visible.
ContainerEvent: Generated when a component is added to or removed from a
to
container.
FocusEvent: Generated when a component gains or loses keyboard focus.
InputEvent: Abstract super class for all component input event classes.
Tu
ItemEvent: Generated when a check box or list item is clicked also occurs whena
choice selection is made or a checkable menu item is selected or deselected.
KeyEvent: Generated when input is received from the keyboard.
MouseEvent: Generated when the mouse is dragged, moved, clicked, pressed,or
released; also generated when the mouse enters or exits a component.
TextEvent: Generated when the value of a text area or text field is changed.
m
notifications about specific types of events.
It must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set ofinterfaces found
co
in java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved.
a.
Any object may receive and process one or both of these events if it providesan
implementation of this interface.
Delegation event model
iy
The modern approach to handling events is based on the delegation event model,
which defines standard and consistent mechanisms to generate and process events.
Its concept is quite simple: a source generates an event and sends it to one or more
un
listeners.
In this scheme, the listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.
sD
The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events.
A user interface element is able to "delegate“ the processing of an event to a
separate piece of code.
al
In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are
sent only to listeners that want to receive them.
ri
This is a more efficient way to handle events than the design used by the old Java 1.0
approach. Previously, an event was propagated up the containment hierarchy until
to
Note:
Java also allows you to process events without using the delegation event
model.
This can be done by extending an AWT component.
m
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
co
void mouseReleased(MouseEvent me)
MouseMotionListener Interface. This interface defines two methods. Their general
forms are :
a.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Handling keyboard events
iy
Keyboard events, can be handled by implementing the KeyListener interface.
KeyListner interface defines three methods. The general forms of thesemethods
are :
un
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
sD
adapter classes and implementing only those events in which you areinterested.
Adapter classes in java.awt.event are.
Adapter Class Listener Interface
Tu
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
m
Inner classes
Inner classes, which allow one class to be defined within another.
An inner class is a non-static nested class. It has access to all of the variables and
co
methods of its outer class and may refer to them directly in the same way thatother
non-static members of the outer class do.
An inner class is fully within the scope of its enclosing class.
a.
an inner class has access to all of the members of its enclosing class, but the reverse
is not true.
Members of the inner class are known only within the scope of the inner class and
iy
may not be used by the outer class
un
The AWT class hierarchy
The AWT classes are contained in the java.awt package. It is one of Java'slargest
packages. some of the AWT classes.
AWT Classes
sD
CardLayout: The card layout manager. Card layouts emulate index cards. Only
the one on top is showing.
Checkbox: Creates a check box control.
to
m
right, top to bottom.
Font: Encapsulates a type font.
FontMetrics: Encapsulates various information related to a font.This
co
information helps you display text in a window.
Frame: Creates a standard window that has a title bar, resize corners, anda
menu bar.
a.
Graphics: Encapsulates the graphics context. This context is used byvarious
output methods to display output in a window.
GraphicsDevice: Describes a graphics device such as a screen or printer.
iy
GraphicsEnvironment: Describes the collection of available Fontand
GraphicsDevice objects.
GridBagConstraints: Defines various constraints relating to theGridBagLayout
un
class.
GridBagLayout: The grid bag layout manager. Grid bag layout displays
components subject to the constraints specified byGridBagConstraints.
sD
GridLayout: The grid layout manager. Grid layout displays components i n a two-
dimensional grid.
Scrollbar: Creates a scroll bar control.
ScrollPane: A container that provides horizontal and/or vertical scrollbarsfor
al
another component.
SystemColor: Contains the colors of GUI widgets such as windows, scrollbars,
text, and others.
ri
m
Label.LEFT, Label.RIGHT, or Label.CENTER
methods are shown here:
void setText(String str)-- specifies the new label
co
String getText( )- -the current label is returned.
void setAlignment(int how) set the alignment of the string within the label
int getAlignment( )-- obtain the current alignment
a.
Label creation: Label one = new Label("One");
Button
The most widely used control is the push button.
iy
A push button is a component that contains a label and that generates an event
when it is pressed.
Push buttons are objects of type Button. Button defines these two constructors:
un
Button( )-- creates an empty button
Button(String str)-- creates a button that contains str as a label
methods are as follows:
sD
is blank.
Scrollbars
Scrollbar generates adjustment events when the scroll bar is manipulated.
Tu
The current value of the scroll bar relative to its minimum and maximum valuesis
indicated by the slider box (or thumb) for the scroll bar.
The slider box can be dragged by the user to a new position. The scroll bar willthen
reflect this value.
Scrollbar defines the following constructors:
Scrollbar( )-- creates a vertical scroll bar
m
Scrollbar(int style)-- to specify the orientation of the scroll bar.
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)-- to
specify the orientation of the scroll bar.
co
If style is Scrollbar.VERTICAL, a vertical scroll bar iscreated.
If style is Scrollbar.HORIZONTAL, the scroll bar ishorizontal
The initial value of the scroll bar is passed in initialValue.
a.
The number of units represented by the height of the thumb is passed
in thumbSize.
The minimum and maximum values for the scroll bar are specifiedby
iy
min and max.
vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, width);
un
Text
Text is created by Using a TextField class
The TextField class implements a single-line text-entry area, usually called anedit
sD
control.
Text fields allow the user to enter strings and to edit the text using the arrow keys,
cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
al
wide.
TextField(String str)- form initializes the text field with the stringcontained
to
in str.
TextField(String str, int numChars)- initializes a text field and sets its width.
Methods
Tu
String getText( )- obtain the string currently contained in the text field
void setText(String str)- To set the text. str is the new string.
Components
At the top of the AWT hierarchy is the Component class.
Component is an abstract class that encapsulates all of the attributes of a visual
component.
All user interface elements that are displayed on the screen and that interactwith
the user are subclasses of Component.
It defines public methods that are responsible for managing events, such asmouse
and keyboard input, positioning and sizing the window, and repainting.
A Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.
m
Component add(Component compObj) -- To add components
Here, compObj is an instance of the control that you want to add.
A reference to compObj is returned.
co
Once a control has been added, it will automatically be visible whenever its parent
window is displayed.
void remove(Component obj) -To remove a control from a window when thecontrol
a.
is no longer needed
Here, obj is a reference to the control you want to remove.
You can remove all controls by calling removeAll( ).
iy
Check box
un
A check box is a control that is used to turn an option on or off. It consists of a small
box that can either contain a check mark or not.
There is a label associated with each check box that describes what option the box
sD
represents.
You can change the state of a check box by clicking on it.
Check boxes can be used individually or as part of a group.
Checkboxes are objects of the Checkbox class.
al
ri
Checkbox( )-
creates a check box whose label is initially blank.
The state of the check box is unchecked.
Tu
Checkbox(String str)- creates a check box whose label is specified by str. The
state of the check
Checkbox(String str, boolean on)-
allows you to set the initial state of the check box.
If on is true, the check box is initially checked; otherwise, it iscleared.
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, booleanon)
m
void setState(boolean on)- To set its state
Here, if on is true, the box is checked. If it is false, the box is cleared.
String getLabel( )-- To retrieve the current label
co
void setLabel(String str)-- To set the label
Checkbox creation:
CheckBox Win98 = new Checkbox("Windows 98", null, true);
a.
Check box groups
It is possible to create a set of mutually exclusive check boxes in which one andonly
iy
one check box in the group can be checked at any one time.
These check boxes are often called radio buttons.
To create a set of mutually exclusive check boxes, you must first define the groupto
un
which they will belong and then specify that group when you construct the check
boxes.
Check box groups are objects of type CheckboxGroup. Only the default constructor is
sD
defined, which creates an empty group.
methods
Checkbox getSelectedCheckbox( ) - determine which check box in a group is
currently selected
al
choose.
A Choice control is a form of menu.
Choice only defines the default constructor, which creates an empty list.
Methods:
void addItem(String name)- add a selection to the list
void add(String name)- add a selection to the list
Here, name is the name of the item being added.
Lists
The List class provides a compact, multiple-choice, scrolling selection list.
List object can be constructed to show any number of choices in the visible window.
m
It can also be created to allow multiple selections.
List provides these constructors:
List( )
co
List(int numRows)
List(int numRows, boolean multipleSelect)
Methods
a.
void add(String name) - add a selection to the list
void add(String name, int index) - add a selection to the list
•Ex: List os = new List(4, true);
iy
Panels
Panel is a window that does not contain a title bar, menu bar, or border.
un
The Panel class is a concrete subclass of Container.
It doesn't add any new methods; it simply implements Container.
A Panel may be thought of as a recursively nestable, concrete screencomponent.
Panel is the superclass for Applet.
Methods
sD
osCards.setLayout(cardLO);
Scroll pane
A scroll pane is a component that presents a rectangular area in which a component
to
may be viewed.
Horizontal and/or vertical scroll bars may be provided if necessary.
Constants are defined by the ScrollPaneConstants interface.
Tu
HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_AS_NEEDED
Dialogs
Dialog class creates a dialog window.
constructors are :
Dialog(Frame parentWindow, boolean mode)
m
list of top-level menu choices. Each choice is associated with a drop-down menu.
To create a menu bar, first create an instance of Menu Bar. By itsdefault
constructor.
Create instances of Menu that will define the selections displayed on the bar.
co
Following are the constructors for Menu:
Menu( )
Menu(String optionName)
a.
Menu(String optionName, boolean removable)
Methods
MenuItem add(MenuItem item) -- add the item to a Menu
iy
Here, item is the item being added. Items are added to a menu in the order in
which the calls to add( ) take place.
Menu add(Menu menu) -- add menu object to the menu bar
Graphics
un
The AWT supports a rich assortment of graphics methods.
All graphics are drawn relative to a window.
A graphics context is encapsulated by the Graphics class
sD
It is passed to an applet when one of its various methods, such as paint( ) orupdate(
), is called.
It is returned by the getGraphics( ) method of Component.
al
The Graphics class defines a number of drawing functions. Each shape can bedrawn
edge-only or filled.
Objects are drawn and filled in the currently selected graphics color, which isblack
ri
by default.
When a graphics object is drawn that exceeds the dimensions of the window, output
is automatically clipped
to
Ex:
Public void paint(Graphics g)
{
Tu
G.drawString(“welcome”,20,20);
}
Layout manager
A layout manager automatically arranges your controls within a window by using
some type of algorithm.
It is very tedious to manually lay out a large number of components and sometimes
the width and height information is not yet available when you need to arrange
some control, because the native toolkit components haven't been realized.
Each Container object has a layout manager associated with it.
A layout manager is an instance of any class that implements the LayoutManager
interface.
The layout manager is set by the setLayout( ) method. If no call to setLayout ( ) is
m
made, then the default layout manager is used.
Whenever a container is resized (or sized for the first time), the layout manageris
used to position each of the components within it.
Different types of layout managers
co
Border Layout
Grid Layout
Flow Layout
a.
Card Layout
GridBag Layout
Border layout
iy
The BorderLayout class implements a common layout style for top-level windows.
It has four narrow, fixed-width components at the edges and one large area in the
center.
un
The four sides are referred to as north, south, east, and west. The middle areais
called the center.
The constructors defined by BorderLayout:
BorderLayout( )
sD
BorderLayout. EAST
BorderLayout.WEST
BorderLayout. NORTH
ri
m
small space is left between each component, above and below, as well as left and
right.
The constructors are
co
FlowLayout( ) - creates the default layout, which centers components andleaves
five pixels of space between each component.
FlowLayout(int how) –
o how specifies that how each line is aligned.
a.
o Valid values for how are:
FlowLayout.LEFT
iy
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout(int how, int horz, int vert)-specifies the horizontal and vertical spaceleft
un
between components in horz and vert, respectively
Card layout
The CardLayout class is unique among the other layout managers in that it stores
several different layouts.
Each layout can be thought of as being on a separate index card in a deck that can be
sD
The cards are held in an object of type Panel. This panel must have CardLayout
selected as its layout manager.
ri
m
co
a.
iy
un
sD
al
ri
to
Tu
UNIT-VI
Java AWT:
Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based
application in java.
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavyweight i.e. its components uses the resources of
m
system.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
co
Java AWT Hierarchy
a.
The hierarchy of Java AWT classes are given below.
iy
un
sD
al
ri
to
Tu
Container classes
These are the predefined classes in java.awt package which can be used to display
all non-container classes to the end user in the frame of window. container classes
are; frame, panel.
m
non-container classes
co
These are the predefined classes used to design the input field so that end user can
provide input value to communicate with java program, these are also treated as
GUI component. non-container classes are; Label, Button, List etc...
a.
non-container classes
iy
These are the predefined classes used to design the input field so that end user can
provide input value to communicate with java program, these are also treated as
GUI component.
un
Label
It can be any user defined name used to identify input field like textbox, textarea etc.
sD
Example
Label l1=new Label("uname");
al
Example
TextField tf=new TextField();
Example
Tu
Example
Button b1=new Button("submit");
TextArea
This class can be used to design a textarea, which will accept number of characters in rows
and columns formate.
m
Example
TextArea ta=new TextArea(5, 10);
co
// here 5 is no. of rows and 10 is no. of column
Note: In above example at a time we can give the contains in textarea is in 5 rows and 9
column (n-1 columns).
a.
Checkbox
iy
This class can be used to design multi selection checkbox.
Example
un
Checkbox cb1=new Checkbox(".net");
Checkbox cb2=new Checkbox("Java");
Checkbox cb3=new Checkbox("html");
sD
This class can be used to design radio button. Radio button is used for single selection.
al
Example
CheckboxGroup cbg=new CheckboxGroup();
ri
Note: Under one group many number of radio button can exist but only one can be selected
at a time.
Tu
Choice
This class can be used to design a drop down box with more options and supports single
selection.
Example
Choice c=new Choice();
c.add(20);
c.add(21);
c.add(22);
c.a dd(23);
List
m
This class can be used to design a list box with multiple options and support multi
selection.
co
Example
List l=new List(3);
l.add("goa");
a.
l.add("delhi");
l.add("pune");
Note: By holding clt button multiple options can be selected.
iy
Scrollbar
un
This class can be used to display a scroolbar on the window.
Example
sD
Type of scrollbar
ri
scrollbar.vertical
scrollbar.horizental
Tu
Example
Scrollbar sb=new Scrollbar(Scrollbar.HORIZENTAL, 10, 5, 0, 100);
Awt Frame
Frame
It is a predefined class used to create a container with the title bar and body part.
m
Example
Frame f=new Frame();
Mostly used methods
co
setTitle()
a.
It is used to display user defined message on title bar.
Example
iy
Frame f=new Frame();
f.setTitle("myframe");
setBackground()
un
It is used to set background or image of frame.
sD
Example
Frame f=new Frame();
f.setBackground(Color.red);
Example
al
setForground()
to
Example
Tu
setSize()
Example
Frame f=new Frame();
f.setSize(400,300);
setVisible()
m
Example
Frame f=new Frame();
co
f.setVisible(true);
Note: You can write setVisible(true) or setVisible(false), if it is true then it visible otherwise
not visible.
a.
setLayout()
iy
It is used to set any layout to the frame. You can also set null layout it means no any layout
apply on frame.
un
Example
Frame f=new Frame();
f.setLayout(new FlowLayout());
sD
Note: Layout is a logical container used to arrange the gui components in a specific order
add()
al
Example
ri
f.add(b);
Explanation: In above code we add button on frame using f.add(b), here b is the object of
Button class..
Tu
Example of Frame
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setTitle("myframe");
f.setBackground(Color.cyan);
f.setForeground(Color.red);
f.setLayout(new FlowLayout());
m
Button b1=new Button("Submit");
Button b2=new Button("Cancel");
f.add(b1);
co
f.add(b2);
f.setSize(500,300);
f.setVisible(true);
a.
}
}
iy
un
sD
al
ri
to
Tu
Introduction to swings
Swing is a set of classes that provides more powerful and flexible componentsthan
are possible with the AWT.
In addition to the familiar components, such as buttons, checkboxes, and labels,
Swing supplies several exciting additions, including tabbed panes, scroll panes,
trees, and tables.
m
Even familiar components such as buttons have more capabilities in Swing.
For example, a button may have both an image and a text string associated withit.
Also, the image can be changed as the state of the button changes.
co
Unlike AWT components, Swing components are not implemented by platform-
specific code.
Instead, they are written entirely in Java and, therefore, are platform-independent.
a.
The term lightweight is used to describe such elements
The Swing component are defined in javax.swing
AbstractButton: Abstract superclass for Swing buttons.
iy
.ButtonGroup: Encapsulates a mutually exclusive set of buttons.
ImageIcon: Encapsulates an icon.
JApplet: The Swing version of Applet.
un
JButton: The Swing push button class.
JCheckBox: The Swing check box class.
JComboBox : Encapsulates a combo box (an combination of a drop-down listand
sD
text field).
JLabel: The Swing version of a label.
JRadioButton: The Swing version of a radio button.
JScrollPane: Encapsulates a scrollable window.
al
m
co
a.
iy
un
sD
al
ri
Model
to
View
View is the front end that user interact.
View can be a
HTML
JSP
Struts ActionForm
Controller
Controller component responsibilities
Receive request from client
Map request to specific business operation
Determine the view to display based on the result of the business operation
m
Difference between AWT and Swing
co
There are many differences between java awt and swing that are given below.
Java AWT Java Swing
AWT components are platform-dependent.
AWT components are heavyweight. Swing components are lightweight.
a.
AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
iy
AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
AWT doesn't follows MVC(Model View
un Swing follows MVC.
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.
sD
Hierarchy of swings
al
ri
to
Tu
The methods of Component class are widely used in java swing that are given below.
Method Description
add a component on another
public void add(Component c)
component.
public void setSize(int width,int
sets size of the component.
height)
m
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean sets the visibility of the component. It is
co
b) by default false.
a.
Java Swing Examples
iy
There are two ways to create a frame:
By creating the object of Frame class (association)
un
By extending Frame class (inheritance)
f.add(b);
f.s etSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
m
Simple(){
f=new JFrame();
JButton b=new JButton("click");
co
b.setBounds(130,100,100, 40);
f.add(b);
f.setSize(400,500);//400 width and 500 height
a.
f.setLayout(null);
f.setVisible(true);
}
iy
public static void main(String[] args)
{ new Simple();
}
un
}
sD
import javax.swing.*;
public class Simple2 extends
JFrame{ JFrame f;
ri
Simple2(){
JButton b=new JButton("click");
to
b.setBounds(130,100,100, 40);
add(b);
setSize(400,500);
Tu
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{ new Simple2();
}
}
Components
Container
JComponent
AbstractButton
JButton
m
JMenuItem
JCheckBoxMenuItem
JMenu
co
JRadioButtonMenuItem
JToggleButton
JCheckBox
a.
JRadioButton
JComponent
JTextComponent
iy
JTextArea
JTextField
JPasswordField
un
JTextPane
JHTMLPane
JComponent
sD
JTextComponent
JTextArea
JTextField
JPasswordField
JTextPane
al
JHTMLPane
Containers
ri
Top-Level Containers
The components at the top of any Swing containment hierarchy
to
Tu
m
co
a.
Special Purpose Container
Intermediate containers that play specific roles in the UI.
iy
un
sD
al
ri
m
f.show();
}
}
co
a.
JComponent
iy
un
• JComponent supports the following components.
JComponent
JComboBox
JLabel
sD
JList
JMenuBar
JPanel
JPopupMenu
al
JScrollBar
JScrollPane
JTextComponent
ri
JTextArea
JTextField
JPasswordField
to
JTextPane
JHTMLPane
Tu
int getIconHeight( )
int getIconWidth( )
void paintIcon(Component comp,Graphics g,int x, int y)
Swing labels are instances of the JLabel class, which extends JComponent.
It can display text and/or an icon.
Constructors are:
JLabel(Icon i)
m
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align argument iseither
LEFT, RIGHT, or CENTER. These constants are defined in the SwingConstants
co
interface,
Methods are:
Icon getIcon( )
a.
String getText( )
void setIcon(Icon i)
void setText(String s)
iy
Here, i and s are the icon and text, respectively.
Text fields
The Swing text field is encapsulated by the JTextComponent class,which
extendsJComponent.
un
It provides functionality that is common to Swing text components.
One of its subclasses is JTextField, which allows you to edit one line of text.
Constructors are:
sD
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the number of
al
the AWT.
Swing buttons are subclasses of the AbstractButton class, whichextends
JComponent.
to
AbstractButton contains many methods that allow you to control the behavior of
buttons, check boxes, and radio buttons.
Methods are:
Tu
String getText( )
void setText(String s)
Here, s is the text to be associated with the button.
JButton
The JButton class provides the functionality of a push button.
JButton allows an icon, a string, or both to be associated with the push button.
Some of its constructors are :
m
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
co
Check boxes
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton.
a.
Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
iy
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
un
JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If stateis
true, the check box is initially selected.
Otherwise, it is not.
sD
The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.
Combo boxes
Swing provides a combo box (a combination of a text field and a drop-down list)
al
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.
Items are added to the list of choices via the addItem( ) method, whose signature
Tu
is:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
Radio Buttons
Radio buttons are supported by the JRadioButton class, which is aconcrete
implementation of AbstractButton.
Some of its constructors are :
JRadioButton(Icon i)
m
If state is true, the button is initially selected.
Otherwise, it is not.
Elements are then added to the button group via the following method:
void add(AbstractButton ab)
co
Here, ab is a reference to the button to be added to the group.
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file cabinet.
a.
Each folder has a title. When a user selects a folder, its contents becomevisible.
Only one of the folders may be selected at a time.
Tabbed panes are commonly used for setting configuration options.
iy
Tabbed panes are encapsulated by the JTabbedPane class, which extends
JComponent. We will use its default constructor. Tabs are defined via thefollowing
method:
un
void addTab(String str, Component comp)
Here, str is the title for the tab, and
comp is the component that should be added to the tab.
Typically, a JPanel or a subclass of it is added.
sD
The general procedure to use a tabbed pane in an applet is outlined here:
Create a JTabbedPane object.
Call addTab( ) to add a tab to the pane.
(The arguments to this method define the title of the tab and the componentit
contains.)
al
if necessary.
Scroll panes are implemented in Swing by the JScrollPane class, whichextends
JComponent. Some of its constructors are :
JScrollPane(Component comp)
Tu
VERTICAL_SCROLLBAR_ALWAYS
.VERTICAL_SCROLLBAR_AS_NEEDED
Here are the steps to follow to use a scroll pane in an applet:
Create a JComponent object.
Create a JScrollPane object.
The arguments to the constructor specify thecomponent and the policiesfor
vertical and horizontal scroll bars.
m
Add the scroll pane to the content pane of the applet.
Trees
Data Model - TreeModel
default: DefaultTreeModel
co
getChild, getChildCount, getIndexOfChild, getRoot, isLeaf
Selection Model - TreeSelectionModel
View - TreeCellRenderer
a.
getTreeCellRendererComponent
Node – DefaultMutableTreeNode
Tables
iy
A table is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to a
new position.
un
Tables are implemented by the JTable class, which extends JComponent.
One of its constructors is :
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be
sD
presented, and
colHeads is a one-dimensional array with the column headings.
Here are the steps for using a table in an applet:
Create a JTable object.
Create a JScrollPane object.
al
The arguments to the constructor specify the table and the policiesfor
vertical and horizontal scroll barsAdd the table to the scroll pane.
Add the scroll pane to the content pane of the applet
ri
to
Tu