Unit 1 Core Java PDF
Unit 1 Core Java PDF
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,
televisions, hand-held remote control named Star 7.
FEATURES OF JAVA
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
• Simple:
– Java was designed to be easy for the professional
programmer to learn and use effectively.
– If you already understand the basic concepts of object-
oriented programming, learning Java will be even easier.
– In Java, there are a small number of clearly defined ways
to accomplish a given task.
• Secure
– Java does not use memory pointers explicitly. All the
programs in java are run under an area known as the
sand box.
– Security manager determines the accessibility options of
a class like reading and writing a file to the local disk.
– Java uses the public key encryption system to allow the
java applications to transmit over the internet in the
secure encrypted form.
– The bytecode Verifier checks the classes after loading.
• Portable
– The feature Write-once-run-anywhere 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. These features makes
the java as a portable language.
• Object Oriented
– Java supports object oriented approach whose important
feature is reusability of code
• Robust
– Java has the strong memory allocation and automatic
garbage collection mechanism.
– It provides the powerful exception handling and type
checking mechanism as compare to other programming
languages.
– Compiler checks the program whether there any error and
interpreter checks any run time error and makes the system
secure from crash.
• Multithreading
– Java was designed to meet the real-world requirement of creating
interactive, networked programs.
• 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
• Usea compiler to translate Java program into an
intermediate language called bytecodes, understood by Java
interpreter (javac Welcome.java)
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
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
structures and algorithms
Block comments may be used at the beginning of each file and before each
method
/*
Here is a block comment
*/
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
int height,width[]; // Not recommended
Error Types
Syntax error / Compile errors
– caught at compile time.
– compiler did not understand or compiler does not
allow
Runtime error
– something “Bad” happens at runtime. Java
breaks these into Errors and Exceptions
Logic Error
– program compiles and runs, but does not do
what you intended or want
Operators
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 <= a) ); b <= a = false
}
}
Logical operator & Unary operator
Operator Name of the Operator Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !(a &&b)
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.println(++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 16-bit Unicode character. Minimum
value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive). Char data type is
used to store any character.
Example: char letterA ='A'
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
The Java programming language defines the following kinds of Variables:
Local Variables
Tied to a method
Tied to an object
Static Variables
Tied to a class
Declaration of Arrays:
– Form 1:
Type arrayname[]
– Form 2:
Type [] arrayname;
– Examples:
int[] students;
69 int students[];
• Declaration:
int myArray [];
• Creation:
71
Arrays – Length
• Arrays are fixed length
• Length is specified at create time
• In java, all arrays store the allocated size in a variable named
“length”.
• We can access the length of arrays as arrayName.length:
e.g. int x = reading.length; // x = 7
• Accessed using the index
e.g. int x = reading [1]; // x = 40
Example
int[] reading = {5, 40, 13, 2, 19, 62, 35};
System.out.println(reading.length);
72
Initializing Array Elements in a Loop
• A for loop is commonly used to initialize array
elements
• For example:
int i;//loop counter/array index
int[] a = new int[10];
for(i = 0; i < a.length; i++)
a[i] = 0;
– note that the loop counter/array index goes from 0
to length - 1
– it counts through length = 10
iterations/elements using the zero-numbering of the
array index
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
74
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values
} 2 0
} 4 0
75
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] = values[i] + values[i- 1 0
1];
2 0
}
3 0
values[0] = values[1] +
values[4]; 4 0
}
}
76
Trace Program with Arrays
i (=1) is less than 5
1 1
for (int i = 1; i < 5; i++) { 0
2
values[i] = i + values[i-1]; 3 0
} 4 0
values[0] = values[1] +
values[4];
}
}
78
Trace Program with Arrays
After i++, i becomes 2
} 2 0
3 0
values[0] = values[1] + values[4]; 4 0
}
}
79
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
} 3 0
} 4 0
80
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
1 1
values[i] = i + values[i-1];
2 3
}
3 0
values[0] = values[1] + values[4];
4 0
}
}
81
Trace Program with Arrays
After this, i becomes 3.
4 0
82
Trace Program with Arrays
i (=3) is still less than 5.
4 0
83
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
84
Trace Program with Arrays
After this, i becomes 4
} 1 1
values[0] = values[1] + values[4]; 2 3
} 3 6
}
4 0
85
Trace Program with Arrays
i (=4) is still less than 5
} 3 6
} 4 0
86
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
88
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];
}
}
89
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
values[i] = i + values[i-1]; 2 3
} 3 6
}
}
90
Copying Arrays
Often, in a program, you need to duplicate an array or a part of an
array. In such cases you could attempt to use the assignment statement
(=), as follows:
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
92
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) … … … … … … …
94
Java Code to Create a 2-D Array
• Syntax for 2-D arrays is similar to 1-D arrays
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
96
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional
Arrays
double[][] x;
97
Two-dimensional Array Illustration
matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3
98
Declaring, Creating, and Initializing Using Shorthand
Notations
99
Lengths of Two-dimensional Arrays
100
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
Circle
centre
Instance variable knows
(state)
radius
setInput()
Methods circumference() does
(behavior) area()
CLASS
Class is declared using the keyword class.
The data or variables, defined within a class are
called as INSTANCE VARIABLES.
Collectively the methods & the variables are
called the members of that class.
Class
class Mobile
// Data Members
String model
String make
String Color
// Methods
call()
receive()
Object
OBJECT PROPERTIES
Identity
The property of an object that distinguishes it from
other objects
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[] args) { public static int max(int num1, int 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.
• That is, the child class inherits the methods and data
defined for the parent class.
120
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
121
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
Association, Aggregation, Composition
4 Employees of a department
Their Manager
HAS-A relationship
//main method
public static void main(String args[]) {
152
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
153
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
…
154
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.*;
157
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.*;
158
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 “abc”).
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body }
159
Using a Package
• Within the current directory (“abc”) store the following code in a
file named “ClassX.java”
import myPackage.ClassA;
160
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
162
Using a Package
• Within the current directory (“abc”) 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
public static void main(String args[])
{
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
163
Adding a Class to a Package
• Consider an existing package that contains a class called
“Teacher”: package pack1;
public class Teacher
{
// class body
}
• This class is stored in “Teacher.java” file within a directory
called “pack1”.
• How do we a new public class called “Student” to this
package.
164
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
166
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;
167
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.
}
168
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
169
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);
170
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);
class 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{
2. System.out.println("ABC".compareTo("ABE"));
System.out.println(date1.compareTo(date2));
178
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;
1.1 try
{ printStackTrace
1.2 getMessage
prints the
method2(); 1.3 printStackTrace
3. method2
}
methods in this order:
2. method1
3. method2
method3
4. method3
4.1 throw
4. method3
public static void method2() throws method2
Exception
{ method1
method3(); 4.1 throw
}
main
(order they were called when exception
public static void method3() throws occurred)
Exception
{
throw new Exception( "Exception thrown in method3" );
} }
Output
Exception thrown in method3
java.lang.Exception: Exception thrown in method3
at UsingExceptions.method3(UsingExceptions.java:28)
at UsingExceptions.method2(UsingExceptions.java:23)
at UsingExceptions.method1(UsingExceptions.java:18)
at UsingExceptions.main(UsingExceptions.java:8)
Thread
• Thread: single sequential flow of control
within a program
• Single-threaded program can handle one task
at any time.
• Multitasking allows single processor to run
several concurrent threads.
• Most modern operating systems support
multitasking.
188
Threads Concept
Multiple Thread 1
threads on
Thread 2
multiple
Thread 3
CPUs
Multiple Thread 1
threads
Thread 2
sharing a
Thread 3
single CPU
189
Threads in Java
Creating threads in Java:
190
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() );
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 forrunning
myThread.start();
Thread Life Cycle
run() destroy()
Ready to
Running Dead
Run/Runnable
notify/ sleep/wait/blocked
Blocking over
Blocked/
Waiting/
Sleeping
Born
Thread States Dead
Ready Or Executing
Runnable or running
run() destroy() or
start() Execution complete
sleepinterval sleep(n)
expires
Sleeping
notify() wait()
notifyAll()
Waiting
I/O Operation
I/O completed
Blocked
sleep() method
Thread.sleep() is a static method. It delays the executing thread for aspecified
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 CPUtime
Will executefirst
4 6
9
Joins
The join method allows one thread to wait for the completion ofanother.
If t1 is a Thread object whose thread is currently executing, t1.join(); causes the
current thread to pause execution until the thread t1terminates.
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 Objectclass.
Typically, there are three ways a developer may use input and
output:
Files and
Directories
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
• Usually works for Characters &Strings
• Reader and Writer are the abstract classes which represent Character
Streams
Stream Byte Streams Character Streams
Object
FileReader FileWriter
System.in
• System.in is the standard input stream.
• The default device is keyboard.
Reading Console Input
Character-orientedstream 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
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 from
data from the File in large chunks the BufferedInputStream.
and stores the data in an internal Data is read from the buffer
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.
It supports operations like readInt, writeInt, readFloat, writeFloat etc,
DataOutputStream
DataInputStream
DataOutputStream
DataOutputStream extends FilterOutputStream,which extends OutputStream
It implements DataOutputinterface.
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 thefile
system named File1.txt
DataOutputStream dos = newDataOutputStream(new
FileOutputStream(“File1.txt"));
DataInputStream
DataInputStream 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 thefile
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
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 core packages
import 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.
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
AWT
Containers and Components
Container (Applet)
Containers (Panels)
Component (Canvas)
Components (Buttons)
Components (TextFields)
Components (Labels)
243
Some types of components
Button Checkbox
Label
Choice Scrollbar
Button
Radio Button
Radio Button Group
Component Class Hierarchy
AWTEvent Container
Panel Applet
Button
Font Window
Canvas Frame
FontMetrics
TextComponent
TextField ScrollPane
Component Label
Scrollbar
LayoutManager
245
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
246
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"));
}
}
248
BorderLayout
• At most five components can be
added
• If you want more components, add a
Panel, then add components to it.
• setLayout (new BorderLayout());
249
BorderLayout with five Buttons
250
Using a Panel
251
GridLayout
• The GridLayout manager divides the container up into
a given number of rows and columns:
252
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"));
}
}
253
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); } 259
drawLine(x1,y1,x2,y2)
g.drawLine(x1,y1,x2,y2);
}
260
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);
}
261
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()
271
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;
277
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);
}
278
}