Unit 1 Core Java_all
Unit 1 Core Java_all
HISTORY OF JAVA
• Java is developed by SUN Microsystems in 1991.
• Created by James Gosling, Patrick Naughton,, Chris
worth, Ed Frank Mike Sheridan.
• Initially it is called as “OAK” and renamed as “JAVA” in
1995
• Java is an object oriented and multi threaded
programming language.
PRIMARY MOTIVATION
General purpose Language, language used for embedded
systems.
Initially used for Consumer Devices like microwave ovens,
• Architecture Neutral
– The feature “write once; run anywhere, any time, forever.”
makes the java language portable provided that the system
must have interpreter for the JVM.
– Java also have the standard data size irrespective of operating
system or the processor.
• Interpreted
– Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java
bytecode.
– This code can be interpreted on any system that provides a
Java Virtual Machine.
• Performance
– Java uses native code usage, and lightweight process called
threads. In the beginning interpretation of bytecode resulted
the performance slow but the advance version of JVM uses the
adaptive and just in time compilation technique that improves
the performance.
• Distributed
• Dynamic
– While executing the java program the user can get the
required files dynamically from a local drive or from a
computer thousands of miles away from the user just by
connecting with the Internet.
A Simple Java Program – The Set Up
4.
1. Select Click on
Path OK
2. Click on
Edit 5.
Click
on OK
CLASSPATH
JVM
JAVA
RUN TIME SYSTEM
BYTE
CODE
(.class)
OPERATING SYSTEM
HARDWARE
Java Architecture (Contd.).
Step1:
Create a java source code with .java extension
Step2:
Compile the source code using java compiler, which will
create bytecode file with .class extension
Step3:
Class loader reads both the user defined and library classes
into the memory for execution
Java Architecture (Contd.).
Step4:
Bytecode verifier validates all the bytecodes are valid and
do not violate Java’s security restrictions
Step5:
JVM reads bytecodes and translates into machine code for
execution. While execution of the program the code will
interact to the operating system and hardware
The 5 phases of Java Programs
Java programs can typically be developed in five stages:
1. Edit
Use an editor to type Java program (Welcome.java)
2. Compile
• Use a compiler to translate Java program into
an intermediate language called bytecodes,
understood by Java interpreter (javac Welcome.java)
• Use a compiler to create .class file, containing bytecodes
(Welcome.class)
3. Loading
Use a class loader to read bytecodes from .class file into memory
The 5 phases of Java Programs (Contd.).
4. Verify
Use a Bytecode verifier to make sure bytecodes are valid and do not
violate security restrictions
5. Execute
• Java Virtual Machine (JVM) uses a combination of interpretation
and just-in-time compilation to translate bytecodes into machine
language
• Applications are run on user's machine, i.e. executed by
interpreter with java command (java Welcome)
Java Virtual Machine
Variable Names
The variables are in mixed case with a lowercase first letter
Variable names should not start with underscore _ or dollar sign $
characters, even though both are allowed
Variable names should be small yet meaningful
One-character variable names should be avoided except for
temporary “throwaway” variables
Eg: int y,myWidth;
Good Programming Practices(Contd.).
Naming Conventions
Method Names
Methods should be verbs, in mixed case with the first letter lowercase, with the
first letter of each internal word capitalized
Eg: void run(), void getColor()
Comments
Block Comments
(optional)
Block
comments
are used to
provide
descriptions
of files,
methods,
*/ data
Good Programming Practices(Contd.).
Comments
Single line Comment
Single line comments can be written using
// Single line
Number per Line
One declaration per line is recommended
int height;
int width;
is preferred over
int height,width;
Do not put different
types on the same line
Error Types
8 Syntax error / Compile errors
– caught at compile time.
– compiler did not understand or compiler does not
allow
8 Runtime error
– something “Bad” happens at runtime. Java
breaks these into Errors and Exceptions
8 Logic Error
– program compiles and runs, but does not do
what you intended or want
Operators
Output:
class Sample{
a + b = 13
public static void main(String[ ] args){ a-b=7
int a = 10; a * b = 30
int b = 3; a/b=3
System.out.println("a + b = " + (a + b) ); a%b=1
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a *
b) ); System.out.println("a / b = " +
(a / b) ); System.out.println("a % b = "
+ (a % b) );
}
}
Relational operator
class Sample{
public static void main(String[] args){
int a = 10;
int b = 20; Output:
System.out.println("a == b = " + (a == b) );
a == b = false
System.out.println("a != b = " + (a != b) ); a != b = true
System.out.println("a > b = " + (a > b) ); a > b = false
System.out.println("a < b = " + (a < b) ); a < b = true
System.out.println("b >= a = " + (b >= a) ); b >= a = true
System.out.println("b <= a = " + (b <= b <= a = false
a) );
}
}
Logical operator & Unary operator
class Sample{
public static void main(String[] args){
boolean a = true;
boolean b = false;
System.out.println("a && b= " + (a&&b));
System.out.println("a || b= " + (a||b));
System.out.println("!(a && b)= "+!a&&b));
}
} Output:
a && b = false
a || b = true
!(a && b) = true
Unary Operator - QUIZ
class Sample{
public static void main(String args[]) Output:
{ int a = 10;
int b = 20; ++a = 11
System.out.println(“++a=”+ (++a));
--b = 19
System.out.println(“--b=”+ (--b));
}
}
Quiz-2
What will be the result, if we try to compile and execute the following code?
class Test {
public static void main(String [ ] args) {
int x=10;
int y=5;
System.out.pri
ntln(++x+(+
+y));
}
}
OUTPUT: 17
bitwise operator
0 0 1 0 1 1 0 1
~ 0 1 0 0 1 1 1 1 & 0 1 0 0 1 1 1 1
1 0 1 1 0 0 0 0 0 0 0 0 1 1 0 1
0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1
^ 0 1 0 0 1 1 1 1 0 1 0 0 1 1 1 1
|
0 1 1 0 0 0 1 0 0 1 1 0 1 1 1 1
Right-Shift and left-shift Operators
• Arithmetic or signed right shift (>>)
operator:
– Examples are:
• 128 >> 1 returns 128/21 = 64
• 256 >> 4 returns 256/24 = 16
• -256 >> 4 returns -256/24 = -16
– The sign bit is copied during the shift.
2. short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A
short is 2 times smaller than an int Default value is 0.
Example: short s = 10000, short r = -20000
3. int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values
unless there is a concern about memory. The default value is 0.
Example: int a = 100000, int b = -200000
4. long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, int b = -200000L
5. float:
Float data type is a single-precision 32-bit floating point.
Float is mainly used to save memory in large arrays of floating
point numbers. Default value is 0.0f.
Example: float f1 = 234.5f
6. double:
double data type is a double-precision 64-bit floating point.
This data type is generally used as the default data type for
decimal values, generally the default choice.
Default value is 0.0d.
Example: double d1 = 123.4d
7. boolean:
Boolean data type represents one bit of information. There are
only two possible values: true and false.
This data type is used for simple flags that track true/false
conditions. Default value is false.
Example: boolean one = true
8. char:
char data type is a single Unicode character. Minimum value is '\
u0000' (or 0). 16-bit
Maximum value is '\uffff' (or 65,535 inclusive). Char data type is
used to store any character.
Example: char letterA ='A'
Quiz
What will be the result, if we try to compile and execute the following code?
class Test
{
public static void main(String [ ] ar)
{
int for=2;
System.out.println(for);
}
}
Quiz
class Test {
public static void main(String [ ]arg)
{
byte b=128;
System.out.println(b);
}
}
Quiz
class Test {
public static void main(String ar[])
{ float f=1.2;
boolean b=1;
System.out.println(f);
System.out.println(b);
}
}
Quiz(Contd.).
class Test {
public static void
main(String ar[])
{ double d=1.2d;
System.out.println(d);
}
}
OUTPUT: 1.2
Quiz(Contd.).
class Test {
public static void main(String [ ] args)
{
int 9A=10;
System.out.println(9A);
}
}
Types of Variables
Tied to a method
Tied to an object
Static Variables
Tied to a class
5 length
a
0 1 2 3 4
Declaration of Arrays:
– Form 1:
Type arrayname[]
– Form 2:
Type [] arrayname;
– Examples:
int[] students;
int students[]; 73
• Declaration:
int myArray [];
• Creation:
Example
int[] reading = {5, 40, 13, 2, 19, 62, 35};
System.out.println(reading.length);
78
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values
79
Trace Program with Arrays
i becomes 1
public class Test {
public static void main(String[]
args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1];
1 0
}
2 0
values[0] = values[1] +
values[4]; 3 0
} 4 0
}
80
Trace Program with Arrays
i (=1) is less than 5
}
}
81
Trace Program with Arrays
After this line is executed, value[1] is 1
2 0
values[i] = i + values[i-1]; 0
3
} 4 0
values[0] = values[1] +
values[4];
}
}
82
Trace Program with Arrays
After i++, i becomes 2
} 2 0
4 0
}
}
83
Trace Program with Arrays
i (= 2) is less than 5
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { After the first iteration
values[i] = i + values[i-1];
} 0 0
1 1
values[0] = values[1] + values[4]; 0
2
} 3 0
} 4 0
84
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
values[i] = i + values[i-1]; 1 1
} 2 3
} 4 0
85
Trace Program with Arrays
4 0
86
Trace Program with Arrays
4 0
87
Trace Program with Arrays
88
Trace Program with Arrays
After this, i becomes 4
89
Trace Program with Arrays
i (=4) is still less than 5
90
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
92
Trace Program with Arrays
i ( =5) < 5 is false. Exit the loop
values[i] = i + values[i-1]; 2 3
} 3 6
values[0] = values[1] + 4 10
values[4];
}
}
93
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
list2 = list1;
Before the assignment After the assignment
list2 = list1; list2 = list1;
list1 list1
Contents Contents
of list1 of list1
list2 list2
Contents Contents
of list2 of list2
Garbage
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
96
Table as a 2-Dimensional Array
• The table assumes a starting balance of $1000
• First dimension: row identifier - Year
• Second dimension: column identifier - percentage
• Cell contains balance for the year (row) and percentage (column)
• Balance for year 4, rate 7.00% = $1311
Indexes 0 1 2 3 4 5
0 $1050 $1055 $1060 $1065 $1070 $1075
1 $1103 $1113 $1124 $1134 $1145 $1156
2 $1158 $1174 $1191 $1208 $1225 $1242
3 $1216 $1239 $1262 $1286 $1311 $1335
Row Index 3 4 $1276 $1307 $1338 $1370 $1403 $1436
(4th row) … … … … … … …
9
Java Code to Create a 2-D Array
• Syntax for 2-D arrays is similar to 1-D arrays
a 0 1 2
102
Lengths of Two-dimensional Arrays
103
Command Line Argument
• The java command-line argument is an argument
i.e. passed at the time of running the java
program.
• The arguments passed from the console can be
received in the java program and it can be used
as an input.
Command Line Argument
class CMD
{
public static void main(String args[])
{
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
System.out.println(args[3]);
System.out.println(args.length);
for(int i=0;i<args.length;i++)
{
System.out.println("args value"+Integer.parseInt(args[i]));
}
}
}
CLASS AND OBJECT
Class
A template that describes the kinds of state and
behavior that objects of its type support.
A class is a blueprint or prototype from which
objects are created.
A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
Object
Object is an instance of a class.
An object is a software bundle of related state and
behavior.
Each object will have its own state, and access to
all of the behaviors defined by its class.
CLASS
A class is a collection of fields (data) and
methods (procedure or function) that operate
on that data.
Circle
centre
Instance radius knows
variable
(state)
setInput()
circumference( does
Methods )
(behavior)
area()
CLASS
Class is declared using the keyword class.
The data or variables, defined within a class
Class
class Mobile
// Data Members
String model
String make
String Color
// Methods
call()
receive()
Object
OBJECT PROPERTIES
Identity
Behavior (methods)
Describes the methods in the object's interface by
which the object can be used.
ADDING FIELDS:
Add fields
pass j
pass i
public static void main(String[] public static int max(int num1, int
args) { num2)
int i = 5; {
int j = 2; int result;
int k = max(i, j);
if (num1 > num2)
System.out.println("The maximum result = num1;
between" +i+ "and“ +j+ "is“ + k); else
} result = num2;
return result;
}
The main method pass 5 The max method
i: 5 num1: 5
pass 2
parameters
j: 2 num2: 2
k: 5 result: 5
Method Overloading
If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading
class Test2{
public static void main(String args[]) {
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
} }
Inheritance
• Inheritance allows a software developer to derive a new
class from an existing one.
• The existing class is called the parent class, or
superclass, or base class.
• The derived class is called the child class or subclass.
• As the name implies, the child inherits characteristics of
the parent.
• That is, the child class inherits the methods and data
defined for the parent class.
125
Inheritance
• Inheritance relationships often are shown
graphically in a UML class diagram, with an
arrow with an open arrowhead pointing to the
parent class
Vehicle
Car
126
Results of Inheritance
public class A
public class B extends A
• the sub class inherits (gains) all instance
variables and instance methods of the super
class, automatically
• additional methods can be added to class B
(specialization)
• the sub class can replace (redefine, override)
methods from the super class
Syntax
class Super
{
.....
.....
}
class Sub extends Super
{
.....
.....
}
class Calculation {
int z;
//main method
public static void main(String args[]) {
}
class A1 {
int i;
public void show(){
System.out.println("A1 (i)="+ i);
}
}
class TestingInheritance{
class TestingInheritance{
G C
M
class Animal{ Class Cow extends Animal{
String name; Cow(int a, int w){
int age; age=a; // this , super
int weight; weight=w; // this , super
Animal(String n, int a,int w){ }
name = n; void display(){
age=a; System.out.println(“Name= Cow \n
weight=w; Age= "+age+” \n weight=”+weight);
} }
void display(){} }
} Class Mammals extends Goat, Cow{
Class Goat extends Animal{
x
String type;
Goat(int a, int w){ Mammals(){
age=a; // this , super //- -----------
weight=w; // this , super }
} }
void display(){
public class Test{
System.out.println(“Name= Goat \n
public static void main(String args[]){
Age= "+age+” \n weight=”+weight);
Mammals m = new Mammals();
}
m.display();
}
}
}
Interfaces
• The general format of an interface definition:
public interface InterfaceName
{
(Method headers...)
}
• All methods specified by an interface are
public by default.
• A class can implement one or more interfaces.
Defining an Interface
An interface is syntactically similar to a class
G C
M
Applying Interfaces (Contd.).
interface IntDemo{
void display();
}
class classOne implements IntDemo{
void add(int x, int y){
System.out.println("The sum
is :" +(x+y));
}
public void display()
{ System.out.println("Welcome to
Interfaces");
}
}
Applying Interfaces (Contd.).
class classTwo implements IntDemo{
void multiply(int i,int j, int k)
{ System.out.println("The result:" +(i*j*k)
);
}
public void display()
{ System.out.println("Welcome to Java
");
}
}
class DemoClass{
public static void main(String args[]) {
classOne c1= new classOne();
c1.add(10,20);
c1.display();
classTwo c2 = new classTwo();
c2.multiply(5,10,15);
c2.display();
}
}
© 2017 confid
wipro.com 1
Wipro ential
Interface References (Contd.).
interface IntDemo{
void display();
}
class classOne implements IntDemo{
void add(int x, int y){
System.out.println("The sum is :" +(x+y));
}
public void display(){
System.out.println("Class one display method ");
}
}
© 2017 confid
wipro.com 1
Wipro ential
Interface References (Contd.).
class classTwo implements IntDemo {
void multiply(int i,int j, int k){
System.out.println("The result:" +
(i*j*k) );
}
public void display(){
System.out.println("Class two
display method" );
}
}
class DemoClass{
public static void main(String args[]){
IntDemo c1= new classOne();
c1.display();
c1 = new classTwo();
c1.display();
}
}
© 2017 confid
wipro.com 1
Wipro ential
Methods of Object class
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait(long timeout,int nanos)throws causes the current thread to wait for the specified
InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException causes the current thread to wait, until another thread
notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
Java packages
• Package: A collection of related classes.
Can also "CONTAIN" sub-packages.
Sub-packages can have similar names,
but are not actually contained inside.
• java.awt does not contain java.awt.event
170
Java Foundation Packages
• Java provides a large number of classes grouped into
different packages based on their functionality.
• The six foundation Java packages are:
java.lang
• Contains classes for primitive types, strings, math functions, threads, and
exception
java.util
• Contains classes such as vectors, hash tables, date etc.
java.io
• Stream classes for I/O
java.awt
• Classes for implementing GUI – windows, buttons, menus etc.
java.net
• Classes for networking
java.applet
• Classes for creating and implementing applets
171
Using System Packages
• The packages are organised in a hierarchical structure. For example,
a package named “java” contains the package “awt”, which in turn
contains various classes required for implementing GUI (graphical
user interface).
java
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt
Graphics awt Package containing
Font classes
Classes containing
Image
methods
…
172
Accessing Classes from
Packages
• There are two ways of accessing the classes stored in
packages:
Using fully qualified class name
• java.lang.Math.sqrt(x);
Import package and use class name directly.
• import java.lang.Math
• Math.sqrt(x);
• Selected or all classes in packages can be imported:
import package.class;
import package.*;
• Implicit in all programs: import java.lang.*;
• package statement(s) must appear first
173
Creating Packages
• Java supports a keyword called “package” for creating user-defined
packages. The package statement must be the first statement in a
Java source file (except comments and white spaces) followed by
one or more classes.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
• Package name is “myPackage” and classes are considered as part
}
of this package; The code is saved in a file called “ClassA.java” and
located in a directory called “myPackage”.
• C://……../JAVA_Code/myPackage/ClassA.java
174
Creating Sub Packages
• Classes in one or more source files can be part of the
same packages.
• As packages in Java are organised hierarchically, sub-
packages can be created as follows:
package myPackage.Math
package myPackage.secondPackage.thirdPackage
• Store “thirdPackage” in a subdirectory named
“myPackage\secondPackage”. Store “secondPackage”
and “Math” class in a subdirectory “myPackage”.
• C://……../JAVA_Code/ myPackage/secondPackage/thirdPackage/..
175
Accessing a Package
• As indicated earlier, classes in packages can be
accessed using a fully qualified name or using a
short-cut as long as we import a corresponding
package.
• The general form of importing package is:
import package1[.package2][…].classname
Example:
• import myPackage.ClassA;
• import myPackage.secondPackage
All classes/packages from higher-level package can be
imported as follows:
• import myPackage.*;
176
Using a Package
• Let us store the code listing below in a file named
“ClassA.java” within subdirectory named “myPackage”
within the current directory (say “JAVA_Codes”).
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body }
177
Using a Package
• Within the current directory (“JAVA_Codes”) store the following
code in a file named “ClassX.java”
import myPackage.ClassA;
178
Compiling and Running
• When ClassX.java is compiled, the compiler
compiles it and places .class file in current
directory. If .class of ClassA in subdirectory
“myPackage” is not found, it complies ClassA
also.
• Note: It does not include code of ClassA into
ClassX
• When the program ClassX is run, java loader
looks for ClassA.class file in a package called
“myPackage” and loads it.
179
Using a Package
• Let us store the code listing below in a file named “ClassA.java”
within subdirectory named “secondPackage” within the current
directory.
package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
180
Using a Package
• Within the current directory (“JAVA_Codes”) store the following
code in a file named “ClassX.java”
import myPackage.ClassA;
import secondPackage.ClassC; Output
public class ClassY Hello, I am ClassA
{ Hello, I am ClassC
182
Adding a Class to a
Package
• Define the public class “Student” and place the package
statement before the class definition as follows:
package pack1;
package pack1;
public class Student
{
class Teacher
// class body
} class Student
• Store this in “Student.java” file under the directory
“pack1”.
• When the “Student.java” file is compiled, the class file
will be created and stored in the directory “pack1”. Now,
the package “pack1” will contain both the classes
“Teacher” and “Student”.
183
Packages and Name
Clashing
• When packages are developed by different organizations, it is
possible that multiple packages will have classes with the same
name, leading to name classing.
package pack1; package pack2;
184
Handling Name Clashing
• In Java, name classing is resolved by accessing classes
with the same name in multiple packages by their fully
qualified name.
• Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;
185
Extending a Class from
Package
• A new class called “Professor” can be created by
extending the “Teacher” class defined the package
“pack1” as follows:
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}
186
Member access modes
in Java
Specifier Class Package Subclass World
Private Y N N N
No Specifier Y Y N N
Protected Y Y Y N
Public Y Y Y Y
187
Member access modes in
Java
188
Abstract Classes
• An Abstract class serves as a superclass for other classes.
• The abstract class represents the generic or abstract form
of all the classes that are derived from it.
• A class becomes abstract when you place the abstract key
word in the class definition.
public abstract class ClassName
189
Abstract Methods
• An abstract method has no body and must be
overridden in a subclass.
• An abstract method is a method that appears in
a superclass, but expects to be overridden in a
subclass.
• An abstract method has only a header and no
body.
AccessSpecifier abstract ReturnType MethodName(ParameterList);
190
Abstract Methods
• Notice that the key word abstract appears in
the header, and that the header ends with a
semicolon.
public abstract void setValue(int value);
• Any class that contains an abstract method is
automatically abstract.
• If a subclass fails to override an abstract method, a
compiler error will result.
• Abstract methods are used to ensure that a
subclass implements the method.
191
/ An abstract class without any abstract method
lass Main {
public static void main(String args[]) {
Derived d = new Derived();
d.fun();
}
Output:
Base fun() called
An abstract class with abstract method
//abstract parent class
abstract class Animal{ Output:
//abstract method
public abstract void sound(); Bark..!
}
//Dog class extends Animal class
public class Dog extends Animal{
Programming through interfaces helps create software solutions that are reusable, extensible,
and maintainable
When you create objects, you refer them through the class references. For example :
ClassOne c1= new classOne(); /* Here, c1 refers to the object of the class
classOne. */
You can also make the interface variable refer to the objects of the class that implements the
interface
The exact method will be invoked at run time
It helps us achieve run-time polymorphism
interface IntDemo{
void display();
}
class classOne implements IntDemo{
void add(int x, int y){
System.out.println("The sum is :" +(x+y));
}
public void display(){
System.out.println("Class one display method ");
}
}
c1.display();
c1 = new classTwo();
c1.display();
}
}
One interface can extend one or more interfaces using the keyword extends
When you implement an interface that extends another interface, you should provide
implementation for all the methods declared within the interface hierarchy
Interface A{}
Interface B{}
Interface C extends A, B{
Abstract Classes can have abstract Interfaces can have only method
methods declarations(abstract methods).
Private Y N N N
No Specifier Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Comparable interface
• This interface imposes a total ordering on the objects of
each class that implements it. This ordering is referred to
as the class's natural ordering, and the class's compareTo
method is referred to as its natural comparison method.
220
EXCEPTION
• An exception is an error condition that changes the normal flow of
control in a program
• Exceptions in Java separates error handling from main business
logic
• When an exception occurs, the statement that would normally
execute next is not executed.
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
• Exception handling
– Method detects error which it cannot deal with
• Throws an exception
– Exception handler
• Code to catch exception and handle it
– Exception only caught if handler exists
• If exception not caught, block terminates
import java.io.File;
import java.io.FileReader;
method2();
1.3 printStackTrace
}
methods in this order: 3. method2
2. method1
3. method2
method3
4. method3
4.1 throw
230
Threads Concept
Multiple T hread 1
threads on
T hread 2
T hread 3
multiple
CPUs
Multiple T hread 1
threads
T hread 2
T hread 3
sharing a
single CPU
231
Threads in Java
Creating threads in Java:
232
Why Multithreading?
Create an object of Thread class and pass a Runnable object (an object of
your class) to it’s constructor.
Thread myThread = new Thread( new MyThreadClass() );
Invoke start method on this object of Thread Class
myThread.start();
Create an object of your class (to initialize the thread by invoking the
superclass constructor)
myThreadClass myThread = new myThreadClass();
Invoke the inherited start() method which makes the thread eligible for running
myThread.start();
Thread Life Cycle
run() destroy()
Ready to
Running Dead
Run/Runnabl
e
notify/ sleep/wait/blocked
Blocking over
Blocked
/
Waiting/
Sleeping
Born
Thread States Dead
Ready Or Executing
or
Runnabl running
run() destroy() or
e
start() Execution
complete
sleep sleep(n)
interval
expires Sleeping
notify() wait()
notifyAll()
Waitin
g
I/O Operation
I/O completed
Blocked
sleep() method
Thread.sleep() is a static method. It delays the executing thread for a
specified period of time (milliseconds or milliseconds plus nanoseconds)
try {
Thread.sleep ( 1000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
Threads with higher priorities are run to completion before Threads with
lower priorities get a chance of CPU time
Join is dependent on the OS for timing, so do not assume that join will
wait exactly as long as you specify.
myThread.join();
System.out.println(“This line is printed after
myThread finishes execution”);
}
}
Synchronization
Sometimes, multiple threads may be accessing the same resources
concurrently
Reading and / or writing the same file
Modifying the same object / variable
cook()
{
//itemName := Userinput
//serve
}
Synchronization
synchronized cook()
{
//itemName := Userinput
//serve
}
wait() & notify()
Threads can communicate using wait() and notify() methods of Object
class.
Console:
(standard-in,
standard-
out)
Socket-
based
sources
Introduction to Streams
A stream is an abstraction that helps a java program to work with external
data
• local file
• user input
• network.
• InputStream and OutputStream are the abstract classes which represent Byte
Streams
Character Stream
Object
FileInputStream, FileOutputStream,
InputStreamReader OutputStreamWriter
DataInputStream DataOutputStrea
m
FileReade FileWriter
r
May be buffered or
unbuffered Abstract Classes
Predefined Stream Objects
The three predefined stream objects in Java are byte streams:
System.out & System.err:
System.in
• System.in is the standard input stream.
• The default device is keyboard.
Reading Console Input
Character-oriented stream can be used to read console input
Java
Program
It is used for operations like making a new empty file, searching for
files, deleting files, making directories etc
Few noteworthy methods in File class
boolean exists() – Returns true if it can find the actual file
boolean createNewFile() – Creates a new file if it doesn’t exist
boolean mkdir() – Creates an empty directory
boolean delete() – Deletes a file
File Streams
File streams are primitive streams whose sources or destinations are
files.
The base file stream classes in java.io package are:
• FileInputStream - binary file input base class
• FileOutputStream - binary file output base class
• FileReader - read text files
• FileWriter - write to text files
All classes provide the read() and write() methods for I/O
operations
File IO Streams
An input stream from a file can be created with:
File file_in = new File ("data.dat");
FileInputStream in = new FileInputStream(file_in);
Java Program
{
BufferedInputStream …..
File FileInputStream …..
Internal Buffer
…..
…..
}
The BufferedInputStream reads We can then read data
data from the File in large from the
chunks and stores the data in BufferedInputStream.
an internal buffer Data is read from the buffer
instead of directly from the file
on each read
Data Streams
The DataInputStream and DataOutputStream allow to read and write
primitive data types to input and output streams respectively, rather than just
bytes or characters
Data streams are buffered. They process more than single byte at a time.
DataOutputStream
DataInputStream
DataOutputStream
DataOutputStream extends FilterOutputStream,which extends OutputStream
This interface defines methods that convert value of primitive type into a byte
and then writes to underlying stream.
Example:
DataOutputStream is attached to a FileOutputStream to write to a file on the file
system named File1.txt
DataOutputStream dos = new DataOutputStream(new
FileOutputStream(“File1.txt"));
DataInputStrea
mDataInputStream is complement of DataOutputStream
This interface reads a sequence of bytes and convert them into values
of primitive type.
Example:
DataInputStream is attached to a FileInputStream to read a file on the
file system named File1.txt
• Java applets
– Compiled Java class files
– Run within a Web browser (or an appletviewer)
– Loaded from anywhere on the Internet
Methods are called in this order
showstatus( String)
JApplet methods that the applet container calls during execution
init( ) Called once by browser when applet is loaded
- initialization of instance variables and GUI components
start( ) Called after init() is finished and every time the browser
returns to HTML page
- starting animations
paint(Graphics g) -called after init() is finished and start() has started, and
every time the applet needs to be repainted. (ie. window
moves.)
-Drawing with the Graphics object
stop ( ) Called when the applet should stop executing (i.e. browser
leaves HTML page.)
Stopping animations
destroy( ) Called when applet is removed from memory (i.e. browser
exists)
- destroy resources allocated to applet
Sample Graphics methods
A Graphics is something you can paint on
g.setColor(Color.red);
Drawing Strings
g.drawString("A Sample String", x, y)
1 // Fig. 3.6: WelcomeApplet.java Outline
2 // A first applet in Java.
3
4 // Java coreimport
packages
allows us to use
5 import java.awt.Graphics; // import class Graphics
6 predefined classes (allowing
7 us to usepackages
// Java extension applets and
8 import javax.swing.JApplet; // import
graphics, in this case). class JApplet
9
10 public class WelcomeApplet extends JApplet {
11
12 // draw text on applet’s background extends allows us to inherit the
13 public void paint( Graphics g ) capabilities of class JApplet.
14 {
15 // call inherited version of method paint
16 super.paint( g );
17 Method paint is guaranteed to
18 // draw a String at x-coordinate 25 and y-coordinate 25
19
be called in all applets. Its
g.drawString( "Welcome to Java Programming!", 25, 25 );
first
20 line must be defined as above.
21 } // end method paint
22
23 } // end class WelcomeApplet
1 <html>
3 </applet>
4 </html>
Strings
String is a sequence of characters enclosed in quotes.
E.g. “Hello”
• String processing is one of the most important and
most frequent applications of a computer
• Java recognizes this fact and therefore provides
special support for strings to make their use
convenient
• Every string is an instance of Java’s built in
String class, thus, Strings are objects.
String
class String_Demo
{
public static void main(String args[])
{
System.out.print("welocome 2025");
System.out.println("Hello world");
int a=23;
float b=23.23489f;
System.out.printf("int=%d and flo=%f",a,b);
System.out.println(a+"welocome 2025"+b);
}
Declaration
Like any object, a string can be created using new as in the following
example:
H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
Examples:
String sub = greeting.substring(0, 4); “Hell”
String w = greeting.substring(7, 12); “ World”
String tail = greeting.substring(7); “ World!”
String Concatenation
• Another common operation on String is concatenation.
• As another special support for String, Java overloaded the +
operator to be used to concatenate two String objects to get a
bigger one.
String firstName = “Computer”;
String lastName = “Science”;
String fullName = firstName+” “+lastName;
//extract initials
String initials =firstName.substring(0,1)+ Output
middleName.substring(0,1)+ Your Password=cse20
lastName.substring(0,1);
//append age
int age = 20;
System.out.println(s1.length());
System.out.println(s1.indexOf("e"));
System.out.println(s1.substring(7, 10));
String s3 = s2.substring(2, 8);
System.out.println(s3.toLowerCase());
OUTPUT
12
8
Reg
rty st
Strings as parameters
public class StringParameters {
public static void main(String[] args) {
sayHello(“Sam");
Output:
Welcome, Sam
Welcome, Helene
String Tokenizer
• StringTokenize
r class in
Java is used to
break a string
into tokens
based on
delimiters.
• A delimiter is a
character or set
of characters
that separate
tokens in the
string.
import java.util.StringTokenizer;
Containers (Panels)
Component (Canvas)
Components (Buttons)
Components (TextFields)
Components (Labels)
291
Some types of components
Button Checkbox
Label
Choice Scrollbar
Button
Radio
Radio Button Group
Button
Component Class Hierarchy
AWTEvent Container
Panel Applet
Button
Font Window
Canvas Frame
FontMetrics
TextComponent
TextField ScrollPane
Component Label
Scrollbar
LayoutManager
293
Arranging components
• Every Container has a layout manager
• The default layout for a Panel is FlowLayout
• An Applet is a Panel
• Therefore, the default layout for a Applet is
FlowLayout
• You could set it explicitly with
setLayout (new FlowLayout( ));
• You could change it to some other layout manager
294
Example: FlowLayout
import java.awt.*;
import java.applet.*;
public class FlowLayoutExample extends
Applet {
public void init () {
setLayout (new FlowLayout ()); // default
add (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));
}
}
296
BorderLayout
• At most five components can be
added
• If you want more components, add a
Panel, then add components to it.
• setLayout (new
BorderLayout());
297
BorderLayout with five
Buttons
public void init() {
setLayout (new BorderLayout ());
add (new Button ("NORTH"), BorderLayout.NORTH);
add (new Button ("SOUTH"), BorderLayout.SOUTH);
add (new Button ("EAST"), BorderLayout.EAST);
add (new Button ("WEST"), BorderLayout.WEST);
add (new Button ("CENTER"), BorderLayout.CENTER);
}
298
Using a Panel
299
GridLayout
• The GridLayout manager divides the container up
into a given number of rows and columns:
300
Example: GridLayout
import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends
Applet {
public void init () {
setLayout(new GridLayout(2, 3));
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}
}
301
How to Use Buttons?
This class represents a push-button which displays some
specified text.
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
How to Use Labels?
public class TestLabel extends Frame {
public TestLabel(String title){
super(title);
Label label1 = new Label();
label1.setText("Label1");
Label label2 = new Label("Label2");
label2.setAlignment(Label.CENTER);
Label label3 = new Label("Label3");
add(label1,"North");
add(label2,"Center");
add(label3,"South");
}
}
How to Use Checkboxes?
public class TestCheckbox extends Frame {
public TestCheckbox(String title){
super(title);
textField.setText("TextField");
textArea.setText("TextArea Line1 \n TextArea Line2");
add(textField,"North");
add(textArea,"South");
}
…}
How to Use Lists?
public class TestList extends Frame {
public TestList(String title){
super(title);
List Li = new List(2, true); //prefer 2 items visible
Li.add("zero");
Li.add(“one”);
Li.add(“two");
Li.add("three");
Li.add(“four");
Li.add(“five");
Li.add("six");
Li.add("seven");
Li.add(“eight");
Li.add(“nine");
Li.add(“ten"); add(Li); } 307
drawLine(x1,y1,x2,y2)
g.drawLine(x1,y1,x2,y2);
}
308
fillOval(x,y,w,h)
drawOval(x,y,w,h)
g.setColor(Color.blue);
{
int x = 239,
y = 186,
w = 48,
h = 32;
g.fillOval(x,y,w,h);
}
309
fillRect(x,y,w,h)
drawRect(x,y,w,h)
g.setColor(Color.pink);
{
int x = 239,
y = 248,
w = 48,
h = 32;
g.fillRect(x,y,w,h);
}
fillRoundRect(x,y,w,h,rw,rh)
drawRoundRect(x,y,w,h,rw,rh)
g.setColor(Color.yellow);
{
int x = 161,
y = 248,
w = 48,
h = 32,
roundW = 25,
roundH = 25;
g.fillRoundRect(x,y,w,h,roundW,roundH);
}
Event handling
For the user to interact with a GUI, the underlying operating system
must support event handling.
1)Operating systems constantly monitor events such as keystrokes,
mouse clicks, voice command, etc.
2) Operating systems sort out these events and report them to the
appropriate application programs
3) Each application program then decides what to do in response
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 in a 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 clicking the
mouse.
• Events may also occur that are not directly caused by
interactions with a user interface.
• 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.
Event Classes in java.awt.event
• ActionEvent
• AdjustmentEvent
• ComponentEvent
• ContainerEvent
• FocusEvent
• InputEvent
• ItemEvent
• KeyEvent
• MouseEvent
• TextEvent
• WindowEvent
Action Events on Buttons
ActionEvent
actionPerformed(..)
Button ActionListener
Example
import java.awt.*;
import java.awt.event.*;
public class TestButtonAction {
public static void main(String[] args){
Frame f = new Frame("TestButton");
f.setSize(200,200);
Button hw = new Button(“Exit!");
f.add(hw);
hw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
f.setVisible(true);
}
}
Some classes and
methods in the event EventObject
hierarchy.
AWTEvent
ActionEvent ComponentEvent
String getActionCommand()
InputEvent WindowEvent
Window getWindow()
MouseEvent KeyEvent
int getX() char getKeyChar()
319
Adapter Class
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter
MouseMotionListener
WindowAdapter WindowListener
MouseAdapter
class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e){}
f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
System.out.println("Mouse clicked: ("+e.getX()+","+e.getY()+")");
}
....
}
import java.applet.Applet;
import java.awt.event.MouseEvent;
Example 2
import java.awt.event.MouseListener;
325
Example
import javax.swing.*;
import java.awt.event.*;
public class CloseDemo2 extends WindowAdapter {
public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setSize(400,100);
f.setVisible(true);
f.addWindowListener(new CloseDemo2());
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
326
}