Java Compiled
Java Compiled
Java Programming
Course Code: IT201
B. Tech. (IT/CSE)
Module-1
1
Books & References
ASET
nlp-ai@cse.iitb
BOOKS ASET
3
OBJECTIVES ASET
Understand the OOP concepts and difference in C++ and Java languages
Differentiate among
- JDK,
- J𝑅𝐸 𝑎𝑛𝑑
- 𝐽𝑉𝑀
Understand the steps for creating, compiling and executing a Java program
4
Introduction ASET
• Java is a high-level programming language originally developed by Sun Microsystems and released
in 1995.
• Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
• Since Oak was already a registered company, so James Gosling and his team changed the Oak
name to Java.
5
Platform? ASET
6
Java: Applications ASET
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games, etc.
7
Why Java? ASET
Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based
on public-key encryption.
Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.
Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java
portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.
Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and
runtime checking.
8
ASET
Multithreaded − With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
Interpreted − Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
9
Java SE Vs. Java EE Vs. Java ME ASET
10
ASET
11
Types of Java Applications ASET
There are mainly 4 types of applications that can be created using Java programming:
2) Web Application- An application that runs on the server side and creates a dynamic page
is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.
4) Mobile Application- An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating mobile applications.
12
ASET
13
Program 1: ASET
S3: Create the java program Using Notepad editor or some other editor.
S4: Save this file as Simple.java
S5: Compile and run the java program.
java Simple
To execute:
16
JVM ASET
18
JDK ASET
19
Can you have multiple classes in a ASET
Yes
20
Java Variables ASET
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
There are three types of variables in java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
1) Local Variable
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
21
ASET
22
ASET
2) Instance Variable
A variable declared inside the class but outside the body of the
method, is called instance variable. It is not declared as static.
It is called instance variable because its value is instance specific
and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It
cannot be local. You can create a single copy of static variable
and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in
the memory.
23
Example: ASET
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
24
Data Types in Java ASET
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
26
Operators in Java ASET
27
ASET
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
28
Some Assignments ASET
nlp-ai@cse.iitb
ASET
End
Thank you…
nlp-ai@cse.iitb
REFRENCES ASET
31
ASET
Java Programming
Course Code: IT201
B. Tech. (IT/CSE)
Module-1
Lecture-2
1
OBJECTIVES ASET
2
Operators in Java ASET
3
Operators in Java ASET
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
4
Operator Examples ASET
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}
}
5
~ and ! ASET
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which
starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
6
<< Vs. >> ASET
class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
7
Logical && vs Bitwise & ASET
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}
8
Ternary Operator ASET
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
9
Modifiers ASET
Modifiers are keywords that you add to those definitions to change their
meanings.
10
Access Control Modifiers ASET
• The synchronized and volatile modifiers, which are used for threads.
12
Control Statements: If Statement ASET
The if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java:
if statement
if-else statement
if-else-if ladder
nested if statement
if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
13
If Statement
ASET
14
Example ASET
15
if-else Statement ASET
The Java if-else statement also tests the condition. It executes the if
block if condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
16
Example ASET
17
if-else-if ladder Statement ASET
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
18
Nested if statement ASET
19
Example ASET
20
Switch Statement ASET
• The switch statement works with byte, short, int, long, enum types,
String and some wrapper types like Byte, Short, Int, and Long.
21
Switch Statement ASET
• The case value must be of switch expression type only. The case
value must be literal or constant. It doesn't allow variables.
• The Java switch expression must be of byte, short, int, long (with its
Wrapper type), enums and string.
23
Switch Statement ASET
Java allows us to use strings in switch expression since Java SE 7. The case
statement should be string literal.
24
Switch Statement ASET
25
Use of Enum ASET
case Wed:
System.out.println("Wednesday");
break;
case Thu:
System.out.println("Thursday");
break;
case Fri:
System.out.println("Friday");
break;
case Sat:
System.out.println("Saturday");
break;
}
}
}
}
27
Some Assignments ASET
3. WAP to check whether a year entered by user is leap year or not. (Hint: A year is
leap, if it is divisible by 4 and 400. But, not by 100.)
4. WAP to create a Grading System for Students. The program will print the grade
according to the marks of student and grading system should include following
grades fail, D grade, C grade, B grade, A grade and A+. (Hint: use if-else ladder)
Thank you…
nlp-ai@cse.iitb
REFRENCES ASET
30
ASET
Java Programming
Course Code: IT201
B. Tech. (IT/CSE)
Module-1
Lecture-3
1
OBJECTIVES ASET
2
LOOPS in Java ASET
3
LOOPS in Java ASET
LOOPS in Java ASET
– for loop
– while loop
– do-while loop
• A simple for loop is the same as C/C++. We can initialize the variable, check condition
and increment/decrement value.
• It consists of four parts:
• Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
• Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
• Statement: The statement of the loop is executed each time until the second
condition is false.
• Increment/Decrement: It increments or decrements the variable value. It is an
optional condition.
LOOPS in Java ASET
Syntax:
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}
Syntax:
for(Type var:array){
//code to be executed
}
Example ASET
Syntax:
while(condition){
//code to be executed
}
do-while Loop ASET
Syntax:
do{
//code to be executed
}while(condition);
Break Statement ASET
Syntax:
jump-statement;
break;
Continue Statement ASET
Syntax:
jump-statement;
continue;
ASET
• The documentation comment is used to create documentation API. To create documentation API,
you need to use javadoc tool.
• This type of comments are used generally when writing code for a project/software package, since
it helps to generate a documentation page for reference, which can be used for getting information
about methods present, its parameters, etc.
Syntax:
/**
This
is
documentation
comment
*/
Example ASET
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
Now, there will be HTML files created for your Calculator class in the current directory. Open the
HTML files and see the explanation of Calculator class provided through documentation comment.
Command Line Arguments ASET
The following example shows how a user might run Echo. User input is in italics.
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
• parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the Number
classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String
representing a number to an object of their type.
Some Assignments ASET
nlp-ai@cse.iitb
ASET
End
Thank you…
nlp-ai@cse.iitb
REFRENCES ASET
30
Classes and Objects
A Java program consists of one or more classes
A class is an abstract description of objects
Here is an example class:
class Dog { ...description of a dog goes here... }
Here are some objects of that class:
1
More Objects
Here is another example of a class:
class Window { ... }
Here are some examples of Windows:
2
Classes contain data definitions
Classes describe the data held by each of its objects
Example: Data usually goes first in a class
class Dog {
String name;
int age;
...rest of the class...
}
A class may describe any number of objects
Examples: "Fido", 3; "Rover", 5; "Spot", 3;
A class may describe a single object, or even no objects at all
3
Classes contain methods
A class may contain methods that describe the behavior of objects
Example:
class Dog { Methods usually go after the data
...
void bark() {
System.out.println("Woof!");
}
}
4
Methods contain statements
A statement causes the object to do something
(A better word would be “command”—but it isn’t)
Example:
System.out.println("Woof!");
This causes the particular Dog to “print” (actually, display on
the screen) the characters Woof!
5
Methods may contain temporary data
Data described in a class exists in all objects of that
class
Example: Every Dog has its own name and age
A method may contain local temporary data that exists
only until the method finishes
Example:
void wakeTheNeighbors( ) {
int i = 50; // i is a temporary variable
while (i > 0) {
bark( );
i = i – 1;
}
}
6
Classes always contain constructors
A constructor is a piece of code that “constructs,” or creates, a
new object of that class
If you don’t write a constructor, Java defines one for you (behind
the scenes)
You can write your own constructors
Example:
class Dog {
(This part is the constructor)
String name;
int age;
Dog(String n, int age) {
name = n;
this.age = age;
}
}
7
Diagram of program structure
Program
Methods
Variables
A program consists of
Statements
one or more classes
Typically, each class is
in a separate .java file
8
Summary
A program consists of one or more classes
A class is a description of a kind of object
In most cases, it is the objects that do the actual work
A class describes data, constructors, and methods
An object’s data is information about that object
An object’s methods describe how the object behaves
A constructor is used to create objects of the class
Methods (and constructors) may contain temporary data
and statements (commands)
9
Writing and running programs
When you write a program, you are writing classes and all the
things that go into classes
Your program typically contains commands to create objects (that
is, “calls” to constructors)
When you run a program, it creates objects, and those objects
interact with one another and do whatever they do to cause
something to happen
Analogy: Writing a program is like writing the rules to a game; running a
program is like actually playing the game
You never know how well the rules are going to work until you
try them out
10
Getting started
Question: Where do objects come from?
Answer: They are created by other objects.
Question: Where does the first object come from?
Answer: Programs have a special main method, not part of any object, that
is executed in order to get things started
public static void main(String[ ] args) {
Dog fido = new Dog("Fido", 5); // creates a Dog
}
The special keyword static says that the main method belongs to
the class itself, not to objects of the class
Hence, the main method can be “called” before any objects are created
Usually, the main method gets things started by creating one or more
objects and telling them what to do
11
Classes & Objects – Part II
Java Programming
Module I
Creating an Object
A class provides the blueprints for objects
An object is created from a class.
In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a
class −
Declaration − A variable declaration with a variable name
with an object type.
Instantiation − The 'new' keyword is used to create the
object.
Initialization − The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.
2
e.g.
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
3
Accessing Instance Variables and Methods
4
public class Puppy {
int puppyAge;
6
Java Package
In simple words, it is a way of categorizing the classes
and interfaces.
When developing applications in Java, hundreds of
classes and interfaces will be written, therefore
categorizing these classes is a must as well as makes life
much easier.
7
Import Statements
In Java if a fully qualified name, which includes the
package and the class name is given, then the compiler
can easily locate the source code or classes.
Import statement is a way of giving the proper location
for the compiler to find that particular class.
E.g.
import java.io.*;
8
import java.io.*; /* Assign the salary to the variable salary.*/
public class Employee { public void empSalary(double empSalary) {
salary = empSalary;
}
String name;
int age; /* Print the Employee details */
String designation; public void printEmployee() {
double salary; System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
// This is the constructor of the class Employee System.out.println("Salary:" + salary);
public Employee(String name) { }
this.name = name; }
}
9
Output:
string
Creating Strings
string
Comparison with character arrays
Although a String has many similarities to an array of characters, there are
some important differences.
You don’t need to use new to create a string unless you want to use one of the
String class constructors
String s1 = "Hello!";
String s2 = new String("Hello!");
You DO NOT use [] to access the characters in the string.
The contents of a String cannot be changed after it has been created.
You can have a String variable refer to a different string, but you cannot
4
Conversion to/from character arrays
To convert from a character array to a String:
char[] x = new char[] {'h','e','l','l','o'};
String s1 = new String( x );
5
String METHODS
string
• public char charAt(int index)
• Returns the character at the specified index. An
index ranges from 0 to length() - 1. The first
character of the sequence is at index 0, the next
at index 1, and so on, as for array indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”
string
⦿ equals() - Compares the invoking string to the specified object.
The result is true if and only if the argument is not null and is a
String object that represents the same sequence of characters
as the invoking object.
string
String myStr1 = "Hello";
String myStr2 = "Hello";
String myStr3 = "Another String";
System.out.println(myStr1.equals(myStr3)); // false
9
• startsWith() – Tests if this string starts with the
specified prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); // true
string
• compareTo() - Compares two strings.
• The result is a negative integer if this String object
lexicographically precedes the argument string.
• The result is a positive integer if this String object
lexicographically follows the argument string.
• The result is zero if the strings are equal.
• compareTo returns 0 exactly when the equals(Object)
method would return true.
public int compareTo(String anotherString) public int
compareToIgnoreCase(String str)
string
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equ
al
System.out.println(s1.compareTo(s3));//-
5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-
1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times
greater than "f"
12
Comparing Strings
What is the value of result for these examples?
Example 1:
String str1 = "abcde" ;
String str2 = "abcfg" ;
int result = str1.compareTo(str2);
Example 2:
String str1 = "abcde" ;
String str2 = "ab" ;
int result = str1.compareTo(str2);
13
• indexOf – Searches for the first occurrence of a character
or substring. Returns -1 if the character does not occur.
string
• substring() - Returns a new string that is a
substring of this string. The substring begins with
the character at the specified index and extends
to the end of this string.
public String substring(int beginIndex)
string
String METHODS
Method call Meaning
S2=s1.toLowerCase() Convert string s1 to lowercase
S2=s1.toUpperCase() Convert string s1 to uppercase
S2=s1.repalce(‘x’, ‘y’) Replace occurrence x with y
S2=s1.trim() Remove whitespaces at the beginning and end
of the string s1
S1.equals(s2) If s1 equals to s2 return true
S1.equalsIgnoreCase(s2) If s1==s2 then return true with irrespective of
case of charecters
S1.length() Give length of s1
S1.CharAt(n) Give nth character of s1 string
S1.compareTo(s2) If s1<s2 –ve no If s1>s2 +ve no If s1==s2 then 0
string
String Operations
returns "together"
string
String Operations
”. replace(‘q', ‘n')
returns “I am an indian"
string
String Operations
string
String Operations
string
StringBuffer
• StringBuffer()
• StringBuffer(int size)
• StringBuffer(String str)
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Methods
Methods Meaning
S1.setCharAt(n, ‘x’) Modify the nth character to x
S1.appen(s2) Append s2 string at the end of s1
S1.insert(n,s2) Insert string s2 in s1 at position n
S1.setLength(n) Set length of string s1 to n
string
e.g.
sb.length(); // 5
sb.capacity(); // 21 (16 characters room is added if no size is
specified)
sb.charAt(1); // e
sb.setCharAt(1,’i’); // Hillo
sb.setLength(2); // Hi
sb.append(“l”).append(“l”); // Hill
In Java, StringTokenizer is used to break a string into tokens based on provided delimiter. Delimiter can be specified
either at the time of object creation or on a per-token basis.
Its object internally maintains a current position within the string to be tokenized. It is located into java.util package.
In string, tokenizer objects are maintained internally and returns a token of a substring from the given string.
31
32
Following are the constructors in string tokenizer
1. StringTokenizer(String str)
2. String nextToken()
33
4. booleanhasMoreElements()
5. Object nextElement()
6. intcountTokens()
Example:
In this example, we are using Stringtokenizer to break string into tokens based on space.
import java.util.StringTokenizer;
34
public class TokenDemo1
{
public static void main(String args[])
{
StringTokenizerobj = new StringTokenizer("Welcome to Java ","
");
while (obj.hasMoreTokens())
{
System.out.println(obj.nextToken());
}
}
}
Output
Welcome to Java
35
Example to understand tokenizer, here we are breaking string into tokens based on the colon (:)
delimiter.
import java.util.*;
public class TokenDemo2{
public static void main(String args[])
{
String a= " : ";
String b= "Welcome : to : Java : . : How : are : You : ?";
StringTokenizer c = new StringTokenizer(b, a);
int count1 = c.countTokens();
for (int i = 0; i<count1; i++)
System.out.println("token [" + i + "] : "
+ c.nextToken());
36
StringTokenizer d= null;
while (c.hasMoreTokens())
System.out.println(d.nextToken());
}
}
37
Chapter : Inheritance
Inheritance
Another fundamental object-oriented technique is
inheritance, used to organize and create reusable classes
2
Inheritance
Inheritance allows a software developer to derive a new
class from an existing one
That is, the child class inherits the methods and data
defined for the parent class
3
Inheritance
To tailor a derived class, the programmer can add new
variables or methods, or can modify the inherited ones
Vehicle
Car
5
Deriving Subclasses
In Java, we use the reserved word extends to establish
an inheritance relationship
6
The protected Modifier
Visibility modifiers determine which class members are
inherited and which are not
Variables and methods declared with public visibility
are inherited; those with private visibility are not
7
The protected Modifier
The protected modifier allows a member of a base class
to be inherited into a child
8
UML Diagram for Words
Book
# pages : int
+ pageMessage() : void
Words Dictionary
- definitions : int
+ main (args : String[]) : void
+ definitionMessage() : void
The super Reference
Constructors are not inherited, even though they have
public visibility
10
The super Reference
A child’s constructor is responsible for calling the parent’s
constructor
13
Overriding
A parent method can be invoked explicitly using the
super reference
15
Class Hierarchies
A child class of one parent can be the parent of another
child, forming a class hierarchy
Business
RetailBusiness ServiceBusiness
16
Class Hierarchies
Two children of the same parent are called siblings
17
The Object Class
A class called Object is defined in the java.lang
package of the Java standard class library
All classes are derived from the Object class
18
The Object Class
The Object class contains a few useful methods, which
are inherited by all classes
For example, the toString method is defined in the
Object class
A semicolon immediately
follows each method header
Interfaces
An interface cannot be instantiated
Methods in an interface have public visibility by
default
A class formally implements an interface by:
• stating so in the class header
• providing implementations for each abstract method in the
interface
// etc.
}
Interfaces
A class that implements an interface can implement
other methods as well
if (obj1.compareTo(obj2) < 0)
System.out.println ("obj1 is less
than obj2");
The Comparable Interface
It's up to the programmer to determine what makes one
object less than another
For example, you may define the compareTo method of
an Employee class to order employees by name
(alphabetically) or by employee number
The implementation of the method can be as
straightforward or as complex as needed for the situation
Requiring Interfaces
Interface names can be used like class names in the
parameters passed to a method
public boolean isLess(Comparable a,
Comparable b)
{
return a.compareTo(b) < 0;
}
Any class that “implements Comparable” can be used
for the arguments to this method
Interfaces in UML
Holiday
Holiday day;
day = new Christmas();
Christmas
47
References and Inheritance
Assigning a predecessor object to an ancestor reference
is considered to be a widening conversion, and can be
performed by simple assignment
48
Polymorphism via Inheritance
It is the type of the object being referenced, not the
reference type, that determines which method is invoked
Suppose the Holiday class has a method called
celebrate, and the Christmas class overrides it
1
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.
2
Runtime Polymorphism in Java
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
3
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
Upcasting in Java
4
class A { }
class B extends A{ }
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type.
For Example:
interface I{ }
class A{ }
class B extends A implements I{ }
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object. 5
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its
run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the subclass method is invoked at
runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
8
(a, b) -> a+b // parameters without types, can be used to sum and concat two strings as well.
(int a, int b) -> return (a+ b); // lambda expression with return statement
(int []) -> {multiple statements; return index;} // it can have multiple statements
In these sample examples, we have variety of lambda expression such as zero argument and single statement, multiple
arguments, lambda with return statement, etc. although return statement is optional and it can have multiple statements as
well.
From Java 8 and later, we can implement such abstract methods using a lambda expression. This is the
strength of lambda expression, notice it does not have any name that's why it is also known as an
anonymous function.
9
Example. (with lambda) Example. (without lambda)
interface Runnable{ interface Runnable{
public void run(); public void run();
} }
public class Demo { public class Demo {
public static void main(String[] args) { public static void main(String[] args) {
int speed=100; int speed=100;
// new approach (lambda expression) to implement // new approach (lambda expression) to implement
Runnable r=()->{ Runnable r= new Runnable(){
System.out.println("Running at the speed of "+speed); System.out.println("Running at the speed of "+speed);
}; };
r.run(); r.run();
} }
} }
10
Output: Running at the speed of 100 Output: Running at the speed of 100
Example: Lambda Expression With Parameter
Lambda Expression can have zero, one, or multiple parameters as we do with methods. Type of parameter is inferred by the
lambda so it is optional, we may or may not mention parameter. See the example wherein second lambda expression we
mentioned type of parameter.
interface Runnable{
public void run (int speed);
}
public class Demo {
public static void main(String[]args) {
int speed=100;
// lambda expression:
Runnable r=(carSpeed)->{
System.out.println("Running at the speed of "+ carSpeed);
}; 11
r.run (speed);
// specifying type of parameters
Runnable r1=(int carSpeed)->{
System.out.println("Running at the speed of "+ carSpeed);
};
r1.run(speed);
}
}
output:
Running at the speed of 100
100
12
Lambda Expression using return Statement
The return statement is optional with a lambda expression. We may use it to return a value to the caller, in this
example, we used two lambda expressions in which first does not use return statement but the second one use
return statement.
interface Runnable {
public String run (int speed, int distance);
}
public class Demo {
public static void main(String[] args) {
1
What is an Applet?
Unlike a Java application program, an applet is specifically designed to be executed within an HTML web document
using an external API.
They are basically small programs – more like the web version of an application – that require a Java plugin to run on
client browser. They run on the client side and are generally used for internet computing.
You can execute a Java applet in a HTML page exactly as you would include an image in a web page. When you see a
HTML page with an applet in a Java-enabled web browser, the applet code gets transferred to the system and is
finally run by the Java-enabled virtual machine on the browser.
2
Applets are also compiled using the javac command but can only run using the applet viewer command or with a
browser.
A Java applet is capable of performing all kinds of operations such as play sounds, display graphics, perform
arithmetic operations, create animated graphics, etc.
You can integrate an applet into a web page either locally or remotely. You can either create your own applets
locally or develop them externally. When stored on a local system, it’s called a local applet.
The ones which are stored on a remote location and are developed externally are called remote applets.
3
Browsers come with Java Runtime environment (JRE) to execute applets and these browsers are called Java-
enabled browsers.
The web page contains tags which specify the name of the applet and its URL (Uniform Resource Locator) – the
unique location where the applet bytecodes reside on the World Wide Web.
In simple terms, URLs refer to the files on some machine or network. Unlike applications, Java applets are
executed in a more restricted environment with harsh security restrictions. They cannot access the resources on the
system except the browser-specific services.
4
What is an Application?
It is a stand-alone Java program that runs with the support of a virtual machine in a client or server side. Also
referred to as an application program, a Java application is designed to perform a specific function to run on any
Java-compatible virtual machine regardless of the computer architecture.
An application is either executed for the user or for some other application program. Examples of Java applications
include database programs, development tools, word processors, text and image editing programs, spreadsheets,
web browsers etc.
5
Java applications can run with or without graphical user interface (GUI). It’s a broad term used to define any kind
of program in Java, but limited to the programs installed on your machine.
Any application program can access any data or information or any resources available on the system without any
security restrictions.
Java application programs run by starting the Java interpreter from the command prompt and are compiled
using the javac command and run using the java command.
Every application program generally stays on the machine on which they are deployed. It has a single start point
which has a main() method.
6
Difference between Application and Applet
Definition of Application and Applet – Applets are feature rich application programs that are specifically designed to be
executed within an HTML web document to execute small tasks or just part of it. Java applications, on the other hand, are
stand-alone programs that are designed to run on a stand-alone machine without having to use a browser.
Execution of Application and Applet– Applications require main method() to execute the code from the command line,
whereas an applet does not require main method() for execution. An applet requires an HTML file before its execution.
The browser, in fact, requires a Java plugin to run an applet.
Compilation of Application and Applet–Application programs are compiled using the “javac” command and further executed
using the java command. Applet programs, on the other hand, are also compiled using the “javac” command but are
executed either by using the “applet viewer” command or using the web browser 7
Security Access of Application and Applet – Java application programs can access all the resources of the system including
data and information on that system, whereas applets cannot access or modify any resources on the system except only
the browser specific services.
Restrictions of Application and Applet – Unlike applications, applet programs cannot be run independently, thus require
highest level of security. However, they do not require any specific deployment procedure during execution. Java
applications, on the other hand, run independently and do not require any security as they are trusted.
8
9
Amity School of Engineering & Technology (CSE)
Module-2
Interfaces
Dr Supriya Raheja
Amity School of Engineering & Technology (CSE)
Learning Objectives
• Interfaces in java
• Diamond problem
• How to implement multiple inheritance in Java
Amity School of Engineering & Technology (CSE)
Interfaces
Important Points
Syntax
Example of interface
Extending Interfaces
interface name2 extends name1 interface Const
{ {
body of name2 int age=35;
} String name=“Supriya”)
}
interface Methods extends Const
{
void display();
}
Amity School of Engineering & Technology (CSE)
Contd…
interface Const
interface combine extends Const, Methods
{
{
int age=35;
………………………..
String name=“Supriya”)
………………………..
}
}
interface Methods
{
void display();
}
Amity School of Engineering & Technology (CSE)
Summary
• Importance of Interfaces
• Different forms of interfaces
• Diamond problem in multiple inheritance
• Solution to Diamond problem
Amity School of Engineering & Technology (CSE)
Module-2
Packages
Faculty: Dr Supriya Raheja
Amity School of Engineering & Technology (CSE)
Packages
Importing Package
//Java is package and util is subpackage
import java.util.*
//import the Vector class from util package
import java.util.Scanner;
// import all the classes from util package
import java.util.*;
Amity School of Engineering & Technology (CSE)
JAVA uses file system to manage Package names are case sensitive. The classes declared within the
packages, with each package stored The directory name and the package package directory will belong to the
in its own directory. name should be the same. specified package.
Amity School of Engineering & Technology (CSE)
//MyCalculator.java //TestPackage.java
package p1; import p1.MyCalculator;
public class MyCalculator{ class TestPackage{
public int Add(int x,int y) public static void main(String[] args)
{ {
return x+y; MyCalculator M = new MyCalculator();
} System.out.print("\n\n\tThe Sum is : " +
public int Subtract(int x,int y) M.Add(45,10));
{ System.out.print("\n\n\tThe Subtract is :" +
return x-y; M.Subtract(45,10));
} System.out.print("\n\n\tThe Product is :" +
M.Product(45,10));
public int Product(int x,int y)
}
{
}
return x*y;
}}
Amity School of Engineering & Technology (CSE)
2
Table of Contents ASET(CSE)
Exception Handling
throw keyword
Finally block
6
Exception class Hierarchy
ASET(CSE)
Exception class Hierarchy
ASET(CSE)
Checked exceptions
• All exceptions other than Runtime Exceptions are known as
Checked exceptions as the compiler checks them during
compilation.
• For example:
SQLException
IOException
ClassNotFoundException etc.
Exception class Hierarchy
ASET(CSE)
Unchecked exceptions
• Runtime Exceptions are also known as Unchecked Exceptions.
• For example:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException etc.
Exception class Hierarchy
ASET(CSE)
Error:
Error is irrecoverable.
Example:
OutOfMemoryError
VirtualMachineError
AssertionError .
Java Exception Keywords ASET(CSE)
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
try
{
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
}
Example
ASET(CSE)
class B
{
public static void main(String args[])
{
int a=0;
int d=5/a;
System.out.println(d);
}
System.out.println(“Program terminated”);
}
class B
{
public static void main(String args[])
{
try
{
int a=0;
int d=5/a;
System.out.println(This will not be printed”);
}
catch(ArithmeticException e)
{ O/P: Division by Zero
System.out.println(e)
After catch block
}
System.out.println(“After catch block”);
}
}
Example
ASET(CSE)
class B
{
public static void main(String args[]) {
try {
int a[ ] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block"); O/P: Exception thrown
:java.lang.ArrayIndexOutOfBoundsExce
} ption: Index 3 out of bounds for length 2
} Out of the block
Multiple Catch block
ASET(CSE)
class B
{
public static void main(String args[]) catch(ArrayIndexOutOfBoundsException
{ e1)
try {
{ System.out.println("Exception thrown
int a=Integer.parseInt(args[0]); :" + e1);
int d=5/a; }
int ar[] = new int[2];
System.out.println("Access element three :" + System.out.println("After catch block");
ar[3]);
} }
catch(ArithmeticException e) }
{
System.out.println(e);
}
Multiple Catch block
ASET(CSE)
• In multiple catch block, exception subclass must come before any of their
superclass.
catch(Exception e)
{
class E
System.out.println("Generic
{ Exception");
}
public static void main(String args[]) catch(ArithmeticException e1)
{ {
System.out.println("no divided by
try zero");
{ }
int a=0; }}
int b=12/a;
System.out.println(b); compile time error: exception ArithmeticException has already
been caught.
} As all the exception will be caught by Exception class, which is
superclass of ArithmeticException class. So we have to reverse
the order of both catch statements.
throw keyword ASET(CSE)
• Syntax:
throw exception;
class B
{
void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Can not give vote – age should be >=18);
}
else
{
System.out.println("Access granted - You are old enough!");
}
} Output:
Exception in thread "main"
public static void main(String[] args) java.lang.ArithmeticException: Can
{ not give vote – age should be >=18
B obj=new B();
obj.checkAge(15);
}
} 19
Throw NullPointerException ASET(CSE)
class Check1
{
public static void main(String args[])
{
Check1 a=new Check1();
a=null;
if(a==null)
throw new NullPointerException("Null");
else
System.out.println("Hello");
}
}
O/P: Exception in thread "main"
java.lang.NullPointerException: Null
Finally block ASET(CSE)
22
Example ASET(CSE)
class Test
{
public static void main(String args[])
{ Output:
try 5
{ Finally block is always executed
int data=25/5; End of Code
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally{System.out.println("finally block is always executed");}
System.out.println(“End of Code");
}
}
Case 2: where exception occurs
and not handled ASET(CSE)
class Test
{
public static void main(String args[])
{
try
{
int data=25/0;
finally block is always executed Exception in
System.out.println(data);
thread "main" java.lang.ArithmeticException:
}
/ by zero
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println(“End of Code"); }
25
}
Case 3: where exception occurs
and handled ASET(CSE)
finally
public class TestFinallyBlock2{ {
public static void main(String args[]) System.out.println("finally block is always
{ executed");
try{ }
System.out.println(“End of Code”);
int data=25/0;
}
System.out.println(data); }
}
catch(ArithmeticException e)
{
System.out.println(e);
java.lang.ArithmeticException: / by zero
}
finally block is always executed
End of code.
Situations When finally block does not
execute ASET(CSE)
27
Diff between throw and throws
ASET(CSE)
throw throws
Java throw keyword is used to explicitly throw Java throws keyword is used to declare
an exception. an exception.
Checked exception cannot be propagated using Checked exception can be propagated
throw only. with throws.
Throw is followed by an instance. Throws is followed by class.
throw new ArithmeticException("Arithmetic throws ArithmeticException;
Exception");
Throw is used within the method. Throws is used with the method
signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException
28
References ASET(CSE)
• https://www.w3schools.com
• https://www.javatpoint.com
29
ASET
1
Objectives ASET
2
Contents ASET
1. What is a Thread ?
2. Creating, Implementing and Extending a Thread
3. The life-cycle of a Thread
4. Interrupt a Thread
5. Thread synchronization
What is a Thread ? ASET
Thread vs Program?
7
Single-Threaded vs Multithreaded ASET
Programs
{ A();
{ A(); A1(); A2(); A3(); newThreads {
B1(); B2(); } { A1(); A2(); A3() };
{B1(); B2() }
}
}
Thread Ecology in a Java ASET
Program
ASET
10
Define and Launch a Java ASET
Thread
• Each Java Run time thread is encapsulated in a
java.lang.Thread instance.
Thread
Steps for extending the Thread class:
1. Subclass the Thread class;
Thread
Implement the Runnable interface :
package java.lang;
public interface Runnable { public void
run() ; }
Define a Thread ASET
// Example:
public class Print2Console extends Thread {
public void run() { // run() is to a thread what
main() is to a java program
for (int b = -128; b < 128; b++)
System.out.println(b); }
… // additional methods, fields …
}
Define a Thread ASET
Ex:
– Printer2Console t1 = new Print2Console(); // t1
is a thread instance !
– t1.start() ; // this will start a new thread, which
begins its execution by calling t1.run()
– … // parent thread continue immediately here
without waiting for the child thread to complete
its execution. cf: t1.run();
– Print2GUI jtext = new Print2GUI();
– Thread t2 = new Thread( jtext);
– t2.start();
– …
An Example ASET
Output??
20
Main Program ASET
Life Cycle of a Java Thread ASET
26
Thread Synchronization ASET
Can Multithreading
incur inconsistency?
29
Multithreading may incur ASET
inconsistency : an Example
Two concurrent deposits of 50 into an account
with 0 initial balance.:
void deposit(int amount) {
int x = account.getBalance();
x += amount;
account.setBalance(x); }
30
Multithreading may incur ASET
inconsistency : an Example
• deposit(50) : // deposit 1 • deposit(50) : // deposit 2
x = account.getBalance() //1 x = account.getBalance() //4
x += 50; //2 x += 50; //5
account.setBalance(x) //3 account.setBalance(x) //6
31
Synchronized Methods and ASET
Statements
• Multithreading can lead to racing hazards where
different orders of interleaving produce different
results of computation.
32
Synchronized Methods and ASET
Statements
• Java’s synchronized method (as well as synchronized
statement) can prevent its body from being
interleaved by relevant methods.
– synchronized( obj ) { … } // synchronized
statement with obj as lock
– synchronized … m(… ) {… } //synchronized
method with this as lock
– When one thread executes (the body of) a
synchronized method/statement, all other threads
are excluded from executing any synchronized
method with the same object as lock. 33
Synchronizing Threads ASET
34
Synchronizing Threads ASET
35
Typical Use ASET
36
Typical Use ASET
37
MODULE IV
ABSTRACT WINDOWING
TOOLKIT (AWT)
By: Dr. Ram Paul Hathwal
Dept of CSE, ASET, AUUP
Department of Computer
Objectives Science and Engineering
AWT – The Abstract Window Toolkit provides basic graphics tools (tools for
putting information on the screen)
Swing – A much better set of graphics tools.
Container – a graphic element that can hold other graphic elements (and is itself
a Component)
Component – a graphic element (such as a Button or a TextArea) provided by a
graphics toolkit
listener – A piece of code that is activated when a particular kind of event occurs
layout manager – An object whose job it is to arrange Components in a
Container.
3
Department of Computer
Abstract Windowing Toolkit Science and Engineering
Component
Button Panel
List
Checkbox
TextComponent TextField
TextArea
Department of Computer
How to build a GUI... Science and Engineering
6
Department of Computer
Component Science and Engineering
Component is the superclass of most of the displayable classes defined within the
AWT. Note: it is abstract.
MenuComponent is another class which is similar to Component except it is the
superclass for all GUI items which can be displayed within a drop-down menu.
The Component class defines data and methods which are relevant to all
Components:
setBounds
setSize
setLocation
setFont
setEnabled
setVisible
setForeground -- colour
setBackground -- colour
Some types of Components Department of Computer
Science and Engineering
Button Checkbox
Label
Scrollbar
Choice
TextField List
TextArea
Button
Checkbox CheckboxGroup
8
Department of Computer
Creating Components Science and Engineering
9
Department of Computer
Container Science and Engineering
The Window class defines a top-level Window with no Borders or Menu bar.
Usually used for application splash screens
When writing a GUI application, the GUI portion can become quite complex.
To manage the complexity, GUIs are broken down into groups of components. Each
group generally provides a unit of functionality.
A Panel is a rectangular Container whose sole purpose is to hold and manage
components within a GUI.
aFrame.add(aPanel);
Department of Computer
Buttons Science and Engineering
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
Department of Computer
Labels Science and Engineering
aPanel.add(aLabel);
Department of Computer
List Science and Engineering
// 5 rows, 80 columns
TextArea fullAddressTextArea = new TextArea(5, 80);
[…
]
Since the Component class defines the setSize() and setLocation() methods, all
Components can be sized and positioned with those methods.
Problem: the parameters provided to those methods are defined in terms of pixels.
Pixel sizes may be different (depending on the platform) so the use of those methods
tends to produce GUIs which will not display properly on all platforms.
Solution: Layout Managers. Layout managers are assigned to Containers. When a
Component is added to a Container, its Layout Manager is consulted in order to
determine the size and placement of the Component.
NOTE: If you use a Layout Manager, you can no longer change the size and location
of a Component through the setSize and setLocation methods.
Department of Computer
Layout Managers (cont) Science and Engineering
There are several different LayoutManagers, each of which sizes and positions its
Components based on an algorithm:
FlowLayout
BorderLayout
GridLayout
For Windows and Frames, the default LayoutManager is BorderLayout. For Panels, the
default LayoutManager is FlowLayout.
Department of Computer
Flow Layout Science and Engineering
The algorithm used by the FlowLayout is to lay out Components like words on a page:
Left to right, top to bottom.
It fits as many Components into a given row before moving to the next row.
The BorderLayout Manager breaks the Container up into 5 regions (North, South,
East, West, and Center).
When Components are added, their region is also specified:
North
South
Department of Computer
Grid Layout Science and Engineering
The GridLayout class divides the region into a grid of equally sized rows and columns.
Components are added left-to-right, top-to-bottom.
The number of rows and columns is specified in the constructor for the LayoutManager.
aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Department of Computer
What if I don’t want a LayoutManager? Science and Engineering
Ch. VIII - 26
Department of Computer
Graphics Science and Engineering
It is possible to draw lines and various shapes within a Panel under the AWT.
Each Component contains a Graphics object which defines a Graphics Context which
can be obtained by a call to getGraphics().
Common methods used in Graphics include:
drawLine
drawOval
drawPolygon •fillOval
drawPolyLine •fillPolygon
drawRect •fillRect
drawRoundRect •fillRoundRect
drawString •setColor
draw3DRect •setFont
fill3DRect •setPaintMode
fillArc •drawImage
MODULE IV
EVENTS HANDLING
Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven.
Event describes the change of state of any object.
Events are generated as result of user interaction with the graphical user
interface components.
Changing the state of an object is known as an event.
For example: clicking on a button, entering a character in Textbox, moving the
mouse, selecting an item from list, scrolling the page, etc.
The java.awt.event package provides many event classes and Listener interfaces
for event handling.
Delegation Event Model Department of Computer
Science and Engineering
The modern approach to handling events is based on the delegation event model.
The delegation event model provides a standard mechanism for a source to generate an event
and send it to a set of listeners.
The listener simply waits until it receives an event.
Once received, the listener processes the event and then return.
In the delegation event model, listener must register with a source in order to receive an event
notification.
Notification are sent only to listeners that want to receive them.
There are mainly three parts in delegation event model.
Events.
Event sources.
Event Listeners.
Department of Computer
Components of Event Handling Science and Engineering
Listeners: A listener is an object that listens to the event. A listener gets notified
when an event occurs.
Events in Java Department of Computer
Science and Engineering
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 clicking the mouse.
Events may also occur that are not directly caused by interactions with a user
interface. We are free to define events that are appropriate for our application.
Department of Computer
Event Sources Science and Engineering
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way.
A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
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 is called addKeyListener().
Department of Computer
Science and Engineering
Conti… Department of Computer
Science and Engineering
When an event occurs, all registered listeners are notified and receive a copy of the event object. This
is known as multicasting the event.
In all cases, notifications are sent only to listeners that register to receive them.
A source must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this:
Here, type is an object that is notified when an event listener. For example, to remove a keyboard
listener, you would call removeKeyListener()
Department of Computer
Sources Generating Events Science and Engineering
Event Listeners Department of Computer
Science and Engineering
It has two major requirements. First, it must have been registered with one or more sources to
receive notifications about specific types of events.
The method that receive and process events are defined in a set of interfaces found in
java.awt.event.
Any object may receive and process one or both of these events if it provides an
implementation of this interface.
Important Event Classes Department of Computer
Science and Engineering
and Interface
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menu-item is selected, list- ActionListener
item is double clicked
MouseEvent generated when mouse is dragged, moved, clicked, pressed or MouseListener
released and also when it enters or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener
TextEvent generated when value of textarea or textfield is changed TextListener
For registering the component with the Listener, many classes provide the registration methods.
For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
Department of Computer
ActionEvent Science and Engineering
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected.
The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event:
public static final int ALT_MASK
• The alt modifier. An indicator that the alt key was held down during the event. (8)
public static final int SHIFT_MASK
• The shift modifier. An indicator that the shift key was held down during the event. (1)
public static final int CTRL_MASK
The control modifier. An indicator that the control key was held down during the event. (2)
public static final int META_MASK
Syntax Example Department of Computer
Science and Engineering
int getModifiers()
Returns the modifier keys held down during this action event.
String paramString()
Returns a parameter string identifying this action event.
Department of Computer
ActionListener Interface Science and Engineering
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
add(Button1);
add(Button2);
if(action.equals("Ok"))
actionMessage = "Ok Button Pressed";
else if(action.equals("Cancel"))
actionMessage = "Cancel Button Pressed";
repaint();
}
}
Output Department of Computer
Science and Engineering
Department of Computer
ComponentEvent class Science and Engineering
A low-level event which indicates that a component moved, changed size, or changed visibility.
This class has following constants.
public static final int COMPONENT_MOVED
This event indicates that the component's position changed.
public static final int COMPONENT_RESIZED
This event indicates that the component's size changed.
public static final int COMPONENT_SHOWN
This event indicates that the component was made visible.
public static final int COMPONENT_HIDDEN
This event indicates that the component was become invisible.
Conti… Department of Computer
Science and Engineering
Parameters:
Component getComponent()
Returns the creator of the event.
the Component object that originated the event, or null if the object is not a Component.
Department of Computer
ComponentListener interface Science and Engineering
void componentResized(ComponentEvent e)
Invoked when the component's size changes.
void componentMoved(ComponentEvent e)
Invoked when the component's position changes
void componentShown(ComponentEvent e)
Invoked when the component has been made visible.
void componentHidden(ComponentEvent e)
Invoked when the component has been made invisible.
Department of Computer
Programming Example Science and Engineering
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
A low-level event which indicates that a container's contents changed because a component was
added or removed
This class has following constants.
public static final int COMPONENT_ADDED
• This event indicates that a component was added to the container.
public static final int COMPONENT_REMOVED
• This event indicates that a component was removed from the container.
public ContainerEvent(Component source, int id, Component child)
• Constructs a ContainerEvent object.
• Parameters:
o source - the Component object (container) that originated the event
o id - an integer indicating the type of event
o child - the component that was added or removed
Conti… Department of Computer
Science and Engineering
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
contentPane.addContainerListener(cont);
frame.setSize(300, 200);
frame.show();
}
}
Output Department of Computer
Science and Engineering
FocusEvent class Department of Computer
Science and Engineering
A low-level event which indicates that a Component has gained or lost the input
focus.
void focusGained(FocusEvent e)
void focusLost(FocusEvent e)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Returns: an integer that indicates whether the item was selected or deselected
Department of Computer
ItemListener interface Science and Engineering
void itemStateChanged(ItemEvent e)
The code written for this method performs the operations that need to occur when
an item is selected (or deselected).
Department of Computer
Programming Example Science and Engineering
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
For example, the KEY_TYPED event for shift + "a" returns the value for "A".
boolean isActionKey()
Returns true if the key firing the event is an action key. Examples of action keys include Page Up,
Caps Lock, the arrow and function keys.
Department of Computer
KeyListener Interface Science and Engineering
Method Purpose
keyTyped(KeyEvent) Called just after the user types a Unicode
character into the listened-to component.
keyPressed(KeyEvent) Called just after the user presses a key while
the listened-to component has the focus.
keyReleased(KeyEvent) Called just after the user releases a key while
the listened-to component has the focus.
Department of Computer
Programming Example Science and Engineering
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
public class EventDemo6 extends JApplet implements KeyListener
{
String event; // description of keyboard event
public void init() // set up UI
{
setLayout(new FlowLayout());
event = ""; addKeyListener(this); // listen for keyboard events
setFocusable(true); // force applet to receive KeyEvent
}
public void paint(Graphics g) // draw message to applet
{
super.paint(g);
g.drawRect(0, 0, getWidth(), getHeight()); // show bounds of applet
g.drawString(event, 10, 50);
}
Conti… Department of Computer
Science and Engineering
Parameters:
• source - the (TextComponent) object that originated the event
◦ void textValueChanged(TextEvent e)
◦ The code written for this method performs the operations that need to occur
when text changes.
Department of Computer
WindowEvent class Science and Engineering
int constants
◦ WINDOW_ACTIVATED
◦ WINDOW_CLOSED
◦ WINDOW_CLOSING
◦ WINDOW_DEACTIVATED
◦ WINDOW_DEICONIFIED
◦ WINDOW_GAINED_FOCUS
◦ WINDOW_ICONIFIED
◦ WINDOW_LOST_FOCUS
◦ WINDOW_OPENED
◦ WINDOW_STATE_CHANGED
Constructors Department of Computer
Science and Engineering
void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window from the window's system menu.
void windowClosed(WindowEvent e)
Invoked when a window has been closed as the result of calling dispose on the window
void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized state.
void windowOpened(WindowEvent e)
Invoked the first time a window is made visible.
void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal state.
void windowActivated(WindowEvent e)
Invoked when the Window is set to be the active Window.
void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window
Department of Computer
WindowFocusListener interface Science and Engineering
void windowGainedFocus(WindowEvent e)
Invoked when the Window is set to be the focused Window, which means that the Window, or
This event indicates a mouse action occurred in a component. This low-level event is generated
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean
popupTrigger)
Method Purpose
Mouse events notify when the user uses the mouse (or similar input device) to interact
with a component.
Mouse events occur when the cursor enters or exits a component's onscreen area and
when the user presses or releases one of the mouse buttons.
Methods of MouseListener Department of Computer
Science and Engineering
Interface
Method Purpose
mouseClicked(MouseEvent) Called just after the user clicks the listened-to
component.
mouseEntered(MouseEvent) Called just after the cursor enters the bounds of
the listened-to component.
mouseExited(MouseEvent) Called just after the cursor exits the bounds of
the listened-to component.
mousePressed(MouseEvent) Called just after the user presses a mouse
button while the cursor is over the listened-to
component.
mouseReleased(MouseEvent) Called just after the user releases a mouse
button after a mouse press over the listened-to
component.
Department of Computer
MouseMotionListener Interface Science and Engineering
Mouse-motion events notify when the user uses the mouse (or a similar input device)
to move the onscreen cursor.
If an application requires the detection of both mouse events and mouse-motion
events, use the MouseInputAdapter class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
repaint();
}
Department of Computer
Science and Engineering
repaint();
}
repaint();
}
Department of Computer
Science and Engineering
repaint();
}
repaint();
}
}
/*<applet code=MouseEventDemo height=300 width=300></applet>*/
Annotations
Introduction
• Java provides feature that enables to embed supplemental information
into the source file.
• This information is called Annotation and does not change the action
of the program
• e.g. @Override
• Annotation leaves the semantics of the program unchanged
Example
class A
{ void show()
{ System.out.print(“Hello”);}
}
class B extends A
{
void show()
{System.out.print(“Bye”)’ }
}
@Smartphone
class NokiaASeries
{
String model;
int size;
}
public class Demo
{
public static void main(String args[])
{
}
}
@interface Smartphone
{
String os() default “Symbian”;
int ver() default 1;
}
Plug-in
A plug-in is bound to a
phase
Lifecycle->Phases-> Goals
Plug-in are mapped to goals and executed as part
of goals
• Project -> Anything that we create in Maven
• Pom.xml is the main file where we describe the dependencies
<project xmlns….
<dependency>
<groupID> com.anchal //unique identifier
<artifactID> demo
<version>
<dependency>
<groupID> org.Springframework </groupID>
<artifactID> Spring-xyz </artifactID>
<version> 4.3.8 release </version>
• groupID
• artifactID
• Version
• http://maven.apache.org/pom.html#Maven_Coordinates
Maven Tutorial Practical
• https://www.youtube.com/watch?v=uEYjXpMDJiU
What is POM?
• A Project Object Model or POM is the fundamental unit of work in
Maven.
• It is an XML file that contains information about the project and
configuration details used by Maven to build the project.
• It contains default values for most projects.
• Example- build directory (target), source directory(src/main/java),
test directory (src/test/java)
• When executing a task or goal, Maven looks for the POM in the
current directory. It reads the POM, gets the needed configuration
information, then executes the goal
Super POM
• http://maven.apache.org/guides/introduction/introduction-to-the-
pom.html
Files and Streams
Goals
To be able to read and write text files
To become familiar with the concepts of text
and binary formats
To learn about encryption
To understand when to use sequential and
random file access
To be able to read and write objects using
serialization
keyboard
standard
input stream
CPU
standard
output MEM
monitor stream
terminal
console
HDD
What does information
travel across?
Streams
keyboard
standard
input stream
CPU
standard
output MEM
monitor stream
terminal file
console input
stream
LOAD HDD
What does information READ
travel across? file
files output
Streams
stream
SAVE
WRITE
Reading and Writing Text Files
Text files – files containing simple text
Created with editors such as notepad, html, etc.
First way:
Use nextInt()
int number = scanner.nextInt();
Second way:
Use nextLine(), Integer.parseInt()
String input = scanner.nextLine();
int number = Integer.parseInt(input);
Numerical Input
Exceptions
nextInt() throws InputMismatchException
parseInt() throws NumberFormatException
Optimal use
nextInt() when there is multiple information on
one line
nextLine() + parseInt() when one number
per line
Reading Files
The same applies for both console input and file
input
Constructors
File(<full path>)
File(<path>, <filename>)
Methods
exists()
canRead(), canWrite()
isFile(), isDirectory()
File Class
java.io.FileReader
Associated with File object
Translates data bytes from File object into a
stream of characters (much like InputStream vs.
InputStreamReader)
Constructors
FileReader( <File object> );
Methods
read(), readLine()
close()
Writing to a File
We will use a PrintWriter object to write to a
file
What if file already exists? Empty file
Doesn’t exist? Create empty file with that name
fout.close();
Closing a File
Why?
When you call print() and/or println(), the
output is actually written to a buffer. When you
close or flush the output, the buffer is written to the
file
The slowest part of the computer is hard drive
operations – much more efficient to write once
instead of writing repeated times
File Locations
When determining a file name, the default is to
place in the same directory as your .class files
If we want to define other place, use an absolute
path (e.g. c:\My Documents)
in = new
FileReader(“c:\\homework\\input.dat”);
Why \\ ?
Sample Program
Two things to notice:
Have to import from java.io
I/O requires us to catch checked exceptions
java.io.IOException
Java Input Review
CONSOLE:
FILE:
FILE:
PrintWriter fout =
new PrintWriter(new File("output.txt");
fout.print("To a file");
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
try{
FileReader reader = new FileReader(inFile);
Scanner in = new Scanner(reader);
PrintWriter out = new
PrintWriter(outputFileName);
int lineNumber = 1;
while (in.hasNextLine()){
String line = in.nextLine();
out.println("/* " + lineNumber + " */ " +
line);
lineNumber++;
}
out.close();
} catch (IOException exception){
System.out.println("Error processing file: "
+ exception);
}
}
}
An Encryption Program
Demonstration: Use encryption to show file
techniques
File encryption
To scramble a file so that it is readable only to those
who know the encryption method and secret
keyword
(Big area of CS in terms of commercial applications
– biometrics, 128-bit encryption breaking, etc.)
Modifications of Output
Two constraints so far:
Files are overwritten
Output is buffered and not written immediately
Constructors
FileWriter( <filename>, <boolean> );
true to append data, false to overwrite all of file
Methods
print(), println(): buffers data to write
flush(): sends buffered output to destination
close(): flushes and closes stream
Java File Output
// With append to an existing file
PrintWriter outFile1 =
new PrintWriter(
new FileWriter(dstFileName,true),false);
Disadvantage
Less efficient – writing to file takes up time, more
efficient to flush once (on close)
Caeser Cipher
Encryption key – the function to change the
value
BankAccount b = . . .;
out.writeObject(b);
Read in an object
readObject returns an Object reference
Need to remember the types of the objects that
you saved and use a cast
It is a checked exception
Constructors
StringTokenizer(String line)//default dlms
StringTokenizer(String ln, String dlms)
Methods
hasMoreTokens()
nextToken()
countTokens()
StringTokenizing in Java
Scanner stdin = new…
System.out.print( "Enter a line with comma
seperated integers(no space): " );
String input = stdin.nextLine();
StringTokenizer st;
String delims = ",";
st = new StringTokenizer( input, delims );
while ( st.hasMoreTokens() )
{
int n = Integer.parseInt(st.nextToken());
System.out.println(n);
}
File gradeFile = new File(“scores.txt”);
if(gradeFile.exists()){
Scanner inFile = new Scanner(gradeFile);
while(line != null){
StringTokenizer st = new
StringTokenizer(line, ":");
System.out.print(" Name: " + st.nextToken());
int num = 0;
double sum = 0;
while ( st.hasMoreTokens() )
{
num++;
sum += Integer.parseInt(st.nextToken());
}
System.our.println(" average = "+ sum/num);
line = inFile.nextLine();
}
inFile.close();
}