0% found this document useful (0 votes)
418 views270 pages

Unit 1 Core Java PDF

Java was developed by Sun Microsystems in 1991. It is an object-oriented programming language that is designed to be portable so that code is written once and can run on any system with a Java Virtual Machine. Some key features of Java include being simple, secure, portable, object-oriented, robust, multithreaded, architecture-neutral, interpreted, high performance, distributed, and dynamic.

Uploaded by

T Akilan Akilan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
418 views270 pages

Unit 1 Core Java PDF

Java was developed by Sun Microsystems in 1991. It is an object-oriented programming language that is designed to be portable so that code is written once and can run on any system with a Java Virtual Machine. Some key features of Java include being simple, secure, portable, object-oriented, robust, multithreaded, architecture-neutral, interpreted, high performance, distributed, and dynamic.

Uploaded by

T Akilan Akilan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 270

Core Java

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.

– To accomplish this, Java supports multithreaded programming,


which allows you to write programs that do many things
simultaneously.

– Multithreading means a single program having different threads


executing independently at the same time.

– Multiple threads execute instructions according to the program


code in a process or a program.

– Multithreading works the similar way as multiple processes run


on one computer.

– In multithreaded programs not even a single thread disturbs the


execution of other thread. Threads are obtained from the pool of
available ready to run threads and they run on the system CPUs.

– This is how Multithreading works in Java.


• Platform Independent
– The concept of Write-once-run-anywhere (known as the
Platform independent) is one of the important key feature of
java language that makes java as the most powerful language.
Not even a single language is idle to this feature but java is
more closer to this feature. The programs written on one
platform can run on any platform provided the platform must
have the JVM.

• 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

– The widely used protocols like HTTP and FTP are


developed in java. Internet programmers can call
functions on these protocols and can get access the files
from any remote machine on the internet rather than
writing codes on their local system.

• 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

 Before we learn about writing a simple java program, let us


understand what preparations are needed for running a java
program from console.

 We have to define PATH and CLASSPATH parameters and


create necessary directories (folders) where we will be
storing all our program files.
PATH

 PATH is an environmental variable in DOS(Disk Operating System),


Windows and other operating systems like Unix.

 PATH tells the operatingsystem which directories(folders) to


search for executable files, in response to commands issued by a user

 It is a convenient way of executing files without bothering about


providing the absolute path to the folder, where the file is located.
How to set PATH ?

1.Right Click My Computer


2.Select Properties
3. You willget to see the Properties
Page of My Computer
4. Select Advanced Tab
5.Select Environment Variables
6. You will see Environment
Variables Page as displayed here.
How to set PATH ? (Contd.).

3. Insert the path to your jdk/bin folder


(e.g. C:\Program Files\Java\JDK
1.6.0_05\bin;

4.
1. Select Click on
Path OK

2. Click on
Edit 5.
Click
on OK
CLASSPATH

• CLASSPATH is a parameter which tells the JVM or the Compiler,


where to locate classes that are not part of Java Development
ToolKit(JDK).

• CLASSPATH is set either on command-line or through environment


variable.

• CLASSPATH set on command-line is temporary in nature, while the


environment variable is permanent.
How to set CLASSPATH ?

1.Right Click My Computer


2.Select Properties
3. You will get to see the
Properties Page of My
Computer
4.Select Advanced Tab
5.Select Environment Variables
6. You will see Environment
Variables Page as displayed
here
How to set CLASSPATH ? (Contd.).
2. Enter “CLASSPATH” as
the variable Name

3. Enter “.” as the Variable


1. Click on New
value
A Simple Java Program
Our first Java Program:

public class Welcome {


public static void main(String args[]) {
System.out.println(“Welcome..!”);
}
} This program displays the output
“Welcome..!”
on the console

Create Source File: Welcome.java


Compile : javac Welcome.java
Execute : java Welcome
Executing your first Java Program
 Before executing the program, just check whether the PATH and the CLASSPATH
parameters are properly set, by typing in the commands as shown in the screen below:
Executing your first Java Program (Contd.).
 Now compile and execute your program as given below :
JAVA ARCHITECHTURE
COMPILE TIME RUN TIME ENVIRONMENT
ENVIRONMENT
Step 3 JAVA
CLASS
Step 1 CLASS
LOADER
JAVA LIBRARIES
SOURCE
CODE Step 4 BYTE
CODE
Java Bytecodes
VERIFIER
Step 2 move locally or Step 5
through
JAVA COMPILER network JUST IN
JAVA TIME
INTERPRETER
COMPILER

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)

• 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

• The output of the compiler is


bytecode
• The bytecodes are executed by
JVM
• It is an interpreter which converts
the specific byte code to machine
instructions and executes
• JVM is platform specific
Keywords
Java reserves some words, which cannot be used as class, method or
variable names.
Good Programming Practices
Naming Conventions
Class Names
 Class names should be nouns, in mixed case with the first
letter of each internal word capitalized
 Class names should be simple and descriptive
 Eg: class Student, class TestStudent

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

Java provides a rich set of operators that can be


categorized under 6 groups of operators
• Arithmetic Operator
• Relational Operator
• Logical Operator
• Unary Operator
• Bitwise Operator
• Assignment Operator
Arithmetic operator

Operator Name of the Operator Example


+ Addition n = n + 1;
- Subtraction n = n-1;
* Multiplication n = n * 1;
/ Division n = n / 1;
% Modulus [Reminder] n = n % 1;
Arithmetic Operators - QUIZ

class Sample{ Output:


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

Operator Name of the Operator Example


== Equal to a == b
!= Not Equal to a != b
> Greater Than a>b
>= Greater Than or equal to a >= b
< Lesser Than a<b
<= Lesser than or equal to a <=b
Relational Operators - QUIZ

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)

Operator Name of the Operator Example


+ Unary plus operator int number = +1;
- Unary minus operator number = - number;
++ Increment operator ++ number;
-- decrement operator -- number;
Logical Operators - QUIZ

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

Operator Description Example


~ Unary bitwise complement ~op2
& Bitwise AND Op1 & Op2
| Bitwise inclusive OR Op1 | Op2
^ Bitwise exclusive OR Op1 ^ Op2
<< Signed left shift Op1 << Op2
>> Signed right shift Op1 >> Op2
Bitwise operator
~  Compliment &  AND
^  XOR |  OR

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.

• Left-shift (<<) operator works as follows:


– 128 << 1 returns 128 * 21 = 256
– 16 << 2 returns 16 * 22 = 64
Example
class BitwiseOper {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
}
}
Right Shift Operator >> QUIZ
class ShiftExample1 {
public static void main(String[] args) {
int x = 16;
System.out.println("The original value of x:"+x);
x = x >> 3;
System.out.println("After >> 3,new value:"+x);
}
}

The original value of x: 16


After >> 3, new value: 2
Left Shift Operator << QUIZ
class ShiftExample2 {
public static void main(String[] args) {
int x =8;
System.out.println("The original value:"+x);
x = x << 4;
System.out.println("After << 4,new value:"+x);
}
}

The original value: 8


After << 4, new value: 128
Assignment operator
Operator Description Equivalent Expression
= x = y;
+= x += y; x = (x + y);
-= x -= y; x = (x - y);
*= x *= y; x = (x * y);
/= x /= y; x = (x / y);
%= x %= y; x = (x % y);
&= x &= y; x = (x & y);
|= x != y; x = (x ! y);
^= x ^= y; x = (x ^ y);
<<= x <<= y; x = (x << y);
>>= x >>= y; x = (x >> y);
Example
class CompAssignDemo{
public static void main(String[] args) {
int x=5;
int y=10; x += y;
System.out.println("The addition is:"+ x);
x -= y;
System.out.println("The subtraction is:"+ x);
x *= y;
System.out.println("The multiplication is:"+ x);
x /= y;
System.out.println("The division is"+ x);
x %= y;
System.out.println("The remainder is:"+x);
x &= y;
System.out.println("The result of AND operation :"+ x);
x |= y;
System.out.println("The result of Bitwise inclusive OR operation :"+ x);
x <<= y;
System.out.println("The result of Signed left shift operation :"+ x);
}
}
DATATYPES
There are eight primitive data types supported by Java
1. byte:
Byte data type is an 8-bit signed two's complement integer. Minimum
value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1) Default value is 0
Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int.
Example: byte a = 100 , byte b = -50

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

 Scope of a local variable is within the method

 Instance Variables (Non-static)

 Tied to an object

 Scope of an instance variable is the whole class

 Static Variables

 Tied to a class

 Shared by all instances of a class


Local Variables
Instance Variables
public class StaticVariable
{ Static Variables
private static String color;
public static String car=“Benz”;

public static void main(String args[])


{
color=“red”;
System.out.println(car+ “ Color: “+color);
}
}
Arrays - Introduction
• An array is a group of contiguous or related data items
that share a common name.

• Used when programs have to handle large amount of data

• Each value is stored at a specific position

• Position is called a index or superscript. Base index = 0

• The ability to use a single name to represent a collection


of items and refer to an item by specifying the item
number enables us to develop concise and efficient
programs.
`
Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array (or)
myList[n-1] references the last element in the array
Declaration of Arrays
• Like any other variables, arrays must declared and created
before they can be used. Creation of arrays involve three
steps:
– Declare the array
– Create storage area in primary memory.
– Put values into the array (i.e., Memory location)

Declaration of Arrays:
– Form 1:
Type arrayname[]
– Form 2:
Type [] arrayname;

– Examples:
int[] students;
69 int students[];
• Declaration:
int myArray [];

• Creation:

myArray = new int[10]; // OR

int myArray [] = new int[10];


Declaring, creating, initializing Using the
Shorthand Notation
double myList[];
myList[] = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the


following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

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);

Output:- displays 7, the length of the array reading

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

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]; 1 0

} 2 0

values[0] = values[1] + values[4]; 3 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

public class Test {


public static void main(String[]
After the array is created
args) {
int[] values = new int[5]; 0 0
for (int i = 1; i < 5; i++) { 1 0
values[i] = values[i] + values[i- 2 0
1]; 3 0
} 4 0

values[0] = values[1] + values[4];


}
}
77
Trace Program with Arrays
After this line is executed, value[1] is 1

public class Test {


public static void main(String[] After the first iteration
args) {
int[] values = new int[5]; 0 0

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

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the first iteration

for (int i = 1; i < 5; i++) {


0 0
values[i] = values[i] + values[i-1]; 1 1

} 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

values[i] = values[i] + values[i-1];


0 0
} 1
1
values[0] = values[1] + values[4]; 2 0

} 3 0

} 4 0

80
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

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.

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the second iteration
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0
}
1 1
values[0] = values[1] + values[4];
} 2 3
} 3 0

4 0

82
Trace Program with Arrays
i (=3) is still less than 5.

public class Test {


public static void main(String[] args) {
After the second iteration
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0
} 1 1
values[0] = values[1] + values[4];
2 3
}
} 3 0

4 0

83
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

public class Test {


public static void main(String[] args) { After the third iteration
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
} 2 3
values[0] = values[1] + values[4]; 3 6
} 4 0
}

84
Trace Program with Arrays
After this, i becomes 4

public class Test {


public static void main(String[] args) {
After the third iteration
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0

} 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

public class Test {


public static void main(String[] args) { After the third iteration
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
0 0
values[i] = i + values[i-1];
1 1
}
3
values[0] = values[1] + values[4]; 2

} 3 6
} 4 0

86
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

public class Test {


public static void After the fourth iteration
main(String[] args) {
int[] values = new int[5]; 0 0
for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3
} 3 6
values[0] = values[1] + 4 10
values[4];
}
}
87
Trace Program with Arrays
After i++, i becomes 5
public class Test {
public static void
main(String[] args) {
int[] values = new int[5]; After the fourth iteration
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0
}
1 1
values[0] = values[1] +
values[4]; 2 3
} 3 6
}
4 10

88
Trace Program with Arrays
i ( =5) < 5 is false. Exit the loop

public class Test {


public static void main(String[] After the fourth iteration
args) {
int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1

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)

public class Test {


public static void main(String[] args)
{
int[] values = new int[5]; 0 11
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 10

}
}
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];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];

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

Balances for Various Interest Rates


Compounded Annually
(Rounded to Whole Dollar Amounts)
Year 5.00% 5.50% 6.00% 6.50% 7.00% 7.50%
1 $1050 $1055 $1060 $1065 $1070 $1075
2 $1103 $1113 $1124 $1134 $1145 $1156
3 $1158 $1174 $1191 $1208 $1225 $1242
4 $1216 $1239 $1262 $1286 $1311 $1335
5 $1276 $1307 $1338 $1370 $1403 $1436
… … … … … … …
93
Column Index 4
Table as a 2-D Array (5th column)

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) … … … … … … …

• Generalizing to two indexes: [row][column]


• First dimension: row index
• Second dimension: column index
• Cell contains balance for the year/row and percentage/column
• All indexes use zero-numbering
– Balance[3][4] = cell in 4th row (year = 4) and 5th column (7.00%)
– Balance[3][4] = $1311 (shown in yellow)

94
Java Code to Create a 2-D Array
• Syntax for 2-D arrays is similar to 1-D arrays

• Declare a 2-D array of ints named table


– the table should have ten rows and six columns
int[][] table = new int[10][6];
Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];

96
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional
Arrays

int[][] matrix = new int[10][10];


or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

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

You can also use an array initializer to declare, create and


initialize a two-dimensional array. For example,

int[][] array = { int[][] array = new int[4][3];


{1, 2, 3}, Same as array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};

99
Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];

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

 A class is a collection of fields (data) and methods


(procedure or function) that operate on that data.

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.

 Basic Syntax for class definition

class ClassName [extends SuperClassName]


{
[fields declaration]
[methods declaration]
}
OBJECTS AND CLASS
Some of the real world objects are,

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

 State (instance variables)


Describes the data stored in the object. Each object
(instance of a class) will have its own unique set of
instance variables as defined in the class.
Collectively, the values assigned to an object's
instance variables make up the object's state.

 Behavior (methods)
Describes the methods in the object's interface by
which the object can be used.
ADDING FIELDS:
 Add fields

public class Circle {


public double x, y; // centre coordinate
public double r; // radius of the circle

 The fields (data) are also called the instance


varaibles.
INTRODUCING METHODS
A method is a collection of statements that are
grouped together to perform an operation.
ADDING METHODS
A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
 Methods are declared inside the body of the
class but immediately after the declaration
of data fields.
 The general form of a method declaration is:

type MethodName (parameter-list)


{
Method-body;
}
ADDING METHODS TO CLASS CIRCLE
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
} Method Body
public double area() {
return 3.14 * r * r;
}
}
CALLING METHODS

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

Different ways to overload the method


There are two ways to overload the method in java

• By changing number of arguments

• By changing the data type


• By changing number of arguments
class Adder{
static int add(int a, int b)
{ return a+b; }
static int add(int a, int b, int c)
{ return a+b+c; }
} OUTPUT
class TestOverloading1 22
{ 33
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
• By changing the data type
class Adder{
static int add(int a, int b)
{ return a+b; } OUTPUT
static double add(double a, double b) 22
{ return a+b; } 24.9
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Method Overriding
 Declaring a method in sub class which is
already present in parent class is known as
method overriding.

 The method in parent class is called


overridden method and the method in child
class is called overriding method.
Method Overriding Example
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating"); OUTPUT:
} Boy is eating
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}}
Advantage of method overriding

The main advantage of method overriding is that the


class can give its own specific implementation to a
inherited method without even modifying the
parent class code.
REAL EXAMPLE OF METHOD OVERRIDING
class Bank{
int getRateOfInterest(){ return 0; }
}

class SBI extends Bank { Output:


int getRateOfInterest() { return 8; } } SBI Rate of Interest : 8
class ICICI extends Bank{ ICICI Rate of Interest: 7
int getRateOfInterest() { return 7; } AXIS Rate of Interest: 9
}

class AXIS extends Bank{


int getRateOfInterest() { return 9; }
}

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.
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

Inheritance should create an is-a relationship, meaning the child is a more


specific version of the parent

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

 These terms are used to signify the relationship between


classes

 They are the basic building blocks of OOPS


Association
 Association is a relationship between two objects
 The association between objects could be
 one-to-one
 one-to-many
 many-to-one
 many-to-many
 Types of Association
 Aggregation
 Composition

 Example: A Student and a Faculty are having an association


Aggregation

 Aggregation is a special case of association


 A directional association between objects
 When an object ‘has-a’ another object, then you have got an
aggregation between them
 Aggregation is also called a “Has-a” relationship.
 Example: College has a Student Object
Composition

• Composition is a special case of aggregation


• In a more specific manner, a restricted aggregation is called
composition
• When an object contains the other object, if the contained object
cannot exist without the existence of container object, then it is
called composition

Example: A class contains students. A student cannot exist without


a class. There exists composition between class and students
IS-A relationship: Manager IS-A Employee

4 Employees of a department

Their Manager
HAS-A relationship

 HAS-A relationship is expressed with containership


 Containership simply means using instance variables that
refer to other objects
Example:
 The class House will have an instance variable which
refers to a Kitchen object
 It means that, House HAS-A Kitchen
 Note that, something like Kitchen HAS-A House is not
valid in this context
HAS-A relationship (Contd.).
 Let us take one personal computer.
 It has a monitor, CPUbox, keyboard and mouse, etc.
 Technically we can say that,
 Personal Computer class HAS-A monitor.
 Personal Computer class HAS-A CPUbox
 Personal Computer class HAS-A keyboard.
 Personal Computer class HAS-A mouse.
 The most important point is : the 4 independent components like
monitor, keyboard, CPUbox and mouse cannot function separately
on its own.
 But, by combining them, we are creating a new type of useful
class called Personal Computer.
Syntax
class Super
{
.....
.....
}
class Sub extends Super
{
.....
.....
}
class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given
numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b); Output
}}
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
The super keyword
• The super keyword is similar to this keyword. Following
are the scenarios where the super keyword is used.

• It is used to differentiate the members of superclass


from the members of subclass, if they have same names.

• It is used to invoke the superclass constructor from


subclass.
class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass Output
Sub_class sub = new Sub_class();
This is the display method of subclass
// Invoking the display() methodThis
of sub class
is the display method of superclass
sub.display(); value of the variable named num in sub class:10
value of the variable named num in super class:20
// Invoking the display() method of superclass
super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+ super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();`
obj.my_method();
}
}
NOTE:

 this(argument list) statement invokes the


constructor of the same class

 first line of a constructor must EITHER be a


super (call on the super class constructor)
OR a this (call on the constructor of same
class)
QUIZ:
class A1 {
A1(){ System.out.println("A1's no arg constructor"); }
A1(int a){ System.out.println("A1's constructor "+ a); }
}
class B1 extends A1{
B1(){System.out.println("B1's no arg constructor"); } B1(int b){super(1000);
System.out.println("B1's constructor "+ b); }
}
class C1 extends B1{
C1() {System.out.println("C1's no arg constructor"); } C1(int c){ super(100);
System.out.println("C1's constructor "+ c); }
}
class TestingInheritance{
public static void main(String args[])
{ OUTPUT
C1 ca = new C1(); A1's no arg constructor
} B1's no arg constructor
}
C1's no arg constructor
class A1 { QUIZ:
A1(){ System.out.println("A1's no arg constructor"); }
A1(int a){ System.out.println("A1's constructor "+ a); }
}
class B1 extends A1{
B1(){ System.out.println("B1's no arg constructor"); }
B1(int b){ super(1000);
System.out.println("B1's constructor "+ b); }
}
class C1 extends B1{
C1() {System.out.println("C1's no arg constructor"); }
C1(int c){ super(100);
System.out.println("C1's constructor "+ c); }
}
class TestingInheritance{ OUTPUT:
public static void main(String args[]){ A1's constructor 1000
C1 ca = new C1(10);
} B1's constructor 100
} C1's constructor 10
Constructors in java
• Constructors are used to initialize the state of an object
when it is created.

• Constructors are invoked while creating objects, usually


after the new keyword.

• A child class may also invoke a super constructor


using the super keyword to initialize the parent object.

• Constructors are similar in syntax to methods, but


without any return type and have the same name as
that of the class (case sensitive).
Rules for defining constructors
1. Constructors have the same name as that of the class.
2. Constructors are similar to methods in syntax, but constructors
do not have a return type; should not even specify void.
A). If you specify return type, then the supposed to be
constructor will become a method and will not be
considered as a constructor.
3. You can have a method with the same name as a constructor.
A). If you specify return type, then it will be considered a
method and will not be invoked during initialization; you need
to invoke it like just any other method.

4. Constructors can also be overloaded just like methods.

A). You may invoke the correct one based on arguments


supplied.
5. A default constructor is a constructor that takes no arguments,
and mostly does nothing.

6. A default constructor with no parameters is automatically added


by Java for a class if there are no user defined constructors.
Example of default constructor

//Java Program to create and call a default constructor


class Bike1{

//creating a default constructor


Bike1()
{ System.out.println("Bike is created"); }

//main method
public static void main(String args[]) {

//calling a default constructor


Bike1 b=new Bike1();
} Output:
}
Bike is created
class Student3{
int id; Example of default constructor
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3(); Output:
0 null
//displaying values of the object 0 null
s1.display();
s2.display();
} }
Java Parameterized Constructor

A constructor which has a specific number of


parameters is called a parameterized constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide
different values to distinct objects. However, you can
provide the same values also.
Example of parameterized constructor
class Student4 {
int id;
String name;
//creating a parameterized constructor
Student4(int i, String n) {
id = i;
name = n;
}
//method to display the values
void display() { System.out.println(id+" "+name); }

public static void main(String args[]) {


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan"); OUTPUT
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object 111 Karan
s1.display(); 222 Aryan
s2.display();
} }
Constructor Overloading in Java
• A constructor is just like a method but without return
type. It can also be overloaded like Java methods.

• Constructor overloading in Java is a technique of having


more than one constructor with different parameter
lists.

• They are arranged in a way that each constructor


performs a different task.

• They are differentiated by the compiler or by the


number of parameters in the list and their types.
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i, String n){
id = i; Output:
name = n; 111 Karan 0
}
//creating three arg constructor 222 Aryan 25
Student5(int i, String n, int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
0 0
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

•Uses of Java packages:


 group related classes together
 as a namespace to avoid name collisions
 provide a layer of access / protection
 keep pieces of a project down to a manageable size
151
Why Using Packages?
• Programmers can easily determine that these classes
and interfaces are related.
• Programmers know where to find classes and
interfaces that provide graphics-related functions.
• The names of classes won’t conflict with class names in
other packages, because the package creates a new
namespace.
• Allow classes within the package to have unrestricted
access to one another yet still restrict access for classes
outside the package.

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.*;

• Implicit in all programs: import java.lang.*;


• package statement(s) must appear first
155
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”.
156
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”.

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;

public class ClassX


{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}

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

•When the program ClassX is run, java loader


looks for ClassA.class file in a package called
“myPackage” and loads it.
161
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");
}
}

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

• 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”.
165
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;

class Teacher class Student

class Student class Courses

• We can import and use these packages like:


 import pack1.*;
 import pack2.*;
 Student student; // Generates compilation error

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);

•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.
171
// An abstract class without any abstract method

abstract class Base {


void fun()
{ System.out.println("Base fun() called"); }
}

class Derived extends Base { }

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{

public void sound(){


System.out.println(“Bark..!"); }
public static void main(String args[]) {
Animal obj = new Dog();
obj.sound();
} }
Interface
 An interface is similar to an abstract class that has all abstract
methods.
 An interface looks similar to a class, except:
the keyword interface is used instead of the keyword class,
and the methods that are specified in an interface have no bodies,
only headers that are terminated by semicolons.
 An interface has comes with the following exceptions:
All methods defined in an interface are abstract.
Interfaces can contain no implementation
Interfaces cannot contain instance variables. However,
they can contain public static final variables (ie. constant
class variables)
 The purpose of an interface is to specify behavior for other
classes.
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.
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.

int compareTo (Object o)


• Compares this object with the specified object for
order. Returns a negative integer, zero, or a
positive integer as this object is less than, equal
to, or greater than the specified object.
Comparable Interface Example

1. System.out.println(new Integer(3).compareTo(new Integer(5)));

2. System.out.println("ABC".compareTo("ABE"));

3. java.util.Date date1 = new java.util.Date(2013, 1, 1);

java.util.Date date2 = new java.util.Date(2012, 1, 1);

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.

Some typical causes of errors:


• Memory errors (i.e. memory incorrectly allocated, memory
leaks, “null pointer”)
• File system errors (i.e. disk is full, disk has been removed)
• Network errors (i.e. network is down, URL does not exist)
• Calculation errors (i.e. divide by 0)
Error handling used for

• Processing exceptional situations


• Processing exceptions for components that cannot
handle them directly
• Processing exceptions for widely used components
(libraries, classes, methods) that should not process their
own exceptions
• Large projects that require uniform error processing
Approaches to handling an exception

1. Prevent the exception from happening


2. Catch it in the method in which it occurs, and
either
a. Fix up the problem and resume normal execution
b. Rethrow it
c. Throw a different exception
3. Declare that the method throws the exception
Exception Classes
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


The Basics of Java Exception Handling

• 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;

public class FilenotFound_Demo {

public static void main(String args[]) {


File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
} Output
C:\>javac FilenotFound_Demo.java
} FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown

FileReader fr = new FileReader(file);


^
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {

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");
} Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
public class UsingExceptions {
public static void main( String args[] )
{
try {
Call method1, which calls
1. main
method1(); method2, which calls
} method3, which throws an
1.1 try
catch ( Exception e ) { exception.
System.err.println( e.getMessage() + "\n" );
1.2 getMessage
e.printStackTrace(); getMessage prints the
} 1.3 printStackTrace
String the Exception
}
was initialized with.
2. method1
public static void method1() throws Exception
1. main

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:

• Extend java.lang.Thread class


OR
• Implement java.lang.Runnable interface

190
Why Multithreading?

• Make the UI more responsive

• Take advantage of multiprocessor systems

• Simplify program logic when there are


multiple independent entities

• Perform asynchronous or background


processing
Using Runnable interface
 Implement Runnable on your class.
class MyThreadClass implements Runnable{…}

 Keep the code to be executed by thread in voidrun()


public void run(){ // code to be executed comes here }

 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 ThreadClass


myThread.start();

 Calling start() method twice will throw IllegalThreadStateException


Using Thread class
 Extend your class with Thread Class
class myThreadClass extends Thread{…}

 Override the run() method of ThreadClass


public void run(){ //Code to be executed by the thread }

 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)

 Thread.sleep() throws a checked InterruptedException if it is interrupted by another


Thread.

try {
Thread.sleep ( 1000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}

 When a thread is asleep, or otherwise blocked on input of some kind, it doesn't


consume CPU time or compete with other threads for processing.
Thread Priorities
 The Thread scheduler which is part of JVM chooses which thread to run
according to a “fixed priority algorithm”

 Threads with higher priorities are run to completion before Threads with
lower priorities get a chance of CPUtime

 The algorithm is preemptive, so if a lower priority thread is running, and


a higher priority thread becomes runnable, the high priority thread will
pre-empt the lower priority thread

 All Java threads have a priority in the range 1-10.


 Thread.MIN_PRIORITY - 1
 Thread.MAX_PRIORITY - 10
 Thread.NORM_PRIORITY - 5
Thread Priority
 When a new Java thread is created it has the same priority as the thread
which created it.
 Thread priority can be changed by the setPriority()method.
t1.setPriority(Thread.NORM_PRIORITY + 1); //priority 6
t2.setPriority(Thread.NORM_PRIORITY -1);//priority 4
t3.setPriority(Thread.MAX_PRIORITY -1);//priority 9
t1.start();
t2.start();
t3.start();
} Will execute last
Will execute second

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.

public class ThreadExampleMain


{
public static void main(String[] args) {
Thread myThread = new ThreadExample(“my data”);
myThread.start();
System.out.println(“I am the mainthread”);

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

 Synchronization controls thread execution order


 Synchronization eliminates data races

 Java has built in primitives to facilitate this coordination


Synchronization

cook()
{
//itemName := Userinput

//query database for recipe

//cook as per the recipe

//serve
}
Synchronization
synchronized cook()
{
//itemName := Userinput

//query database for recipe

//cook as per the recipe

//serve
}
wait() & notify()
 Threads can communicate using wait() and notify() methods of Objectclass.

 Both of them can be invoked only within a synchronized context

 When a thread calls the wait() method:


• The thread releases the lock forthe object.
• The state of the thread is set to beblocked.
• The thread is placed in the wait set for the object.

 When a thread calls the notify()method:


• An arbitrary thread is picked from the list of threads in the wait set.
• Moves the selected thread from the wait set to the entry set.
• Sets the state of the selected thread from blocked to runnable.

• notifyall() will move all waiting threads to Runnable state


wait() & notify()
Burger

synchronized takeOrder() synchronized prepareOrder()


{ {
try{ if(!orderTaken) {
if(!orderPrepared) { wait();
wait(); }
} orderPrepared = true;
orderTaken = true; orderTaken=false;
orderPrepared=false; notify();
notify(); }catch(InterruptedException ie) {
} catch(InterruptedException ie) { ie.printStackTrace();
ie.printStackTrace(); }
} }
}
I/O Application

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.

Java Program InputStream


{ File.txt
…..
…..
…..
…..
} OutputStream
I/O Streams

• A program uses an input stream to read data from a source, one


item at a time.

• A program uses an output stream to write data to a destination


(sink), one item at time.
Types of Streams
 Byte Stream

• Byte streams provide an abstraction to read/write bytes, e.g. binarydata

• InputStream and OutputStream are the abstract classes which represent Byte
Streams

 Character Stream
• Usually works for Characters &Strings

• Follows the Unicode to support internationalization

• Reader and Writer are the abstract classes which represent Character
Streams
Stream Byte Streams Character Streams

Source streams InputStream Reader

Sink streams OutputStream Writer


IO Class Hierarchy

Object

OutputStream InputStream Reader Writer

Byte-Oriented Streams Character-OrientedStreams


Stream Hierarchy
I/O Streams

Byte Oriented Streams Unicode Character Oriented Streams

InputStream OutputStream Reader Writer

FileInputStream, FileOutputStream, InputStreamReader OutputStreamWriter


DataInputStream DataOutputStream

FileReader FileWriter

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.out refers to standard output stream and System.err refers to


standard error stream
• The default device for both these streams is console

 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

 The keyboard sends data to the InputStream (System.in)which is connected to


InputStreamReader stream which is further connected to a BufferedReader
stream.

BufferedReader stdin = newBufferedReader(new


InputStreamReader(System.in));

Java
Program

Note: java.util.Scanner can also be used for reading inputs


File class
 Objects of type File are used to represent the actual files or directories on the
disk

 File class is not actually used to read/write data

 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 emptydirectory
 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);

 Output streams to files are opened like:


File file_out = new File("tmp.dat");
FileOutputStream out = new FileOutputStream (file_out);

 To append to an existing file use the overloaded constructor:


File file_out = new File ("old.dat");
FileOutputStream out =new FileOutputStream(file_out, true);
Buffered IO Streams
 We can wrap a BufferedInputStream or BufferedOutputStream around the
FileInputStream or FileOutputStream for reading & storing large chunks of data
in a buffer at once for later use

FileInputStream fin = new FileInputStream(“data.dat”);


BufferedInputStream bins = new BufferedInputStream(fin);

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.

 DataOutputStream must be attached to some other OutputStream.

 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

 It extends FilterInputStream, which extends InputStream.

 It implements DataInput interface.

 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

DataInputStream dis = newDataInputStream(new


FileInputStream(“File1.txt"));
Java Applet
• Java applications
– Run in stand-alone mode
– No additional software required (such as a Web browser)

• 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

• init and destroy are only


init()
called once each
start()
• start and stop are called
whenever the browser enters and
paint
leaves the page
do other work • do some work is code called by your
listeners
stop()
• paint is called again when the
applet needs to be repainted
destroy()
Application vs Applets
Application Applet
• Inherits from JFrame • Inherits from JApplet

• Has a constructor • Uses an init method that


performs the same operations as
a constructor.
• Requires calls to setSize, • An applet does not have a
setDefaultCloseOperation, window of its own so it does NOT
and setVisible to establish require calls to these methods.
window
• Requires a static main • There is no main() method -- the
method to create an browser creates an instance of
instance of the application. the class automatically.
Different Parts of An Applet
Inherit applet methods from class JApplet
JApplet
public void init( )
YourApplet public void start()

public void paint(Graphics g) public void paint(Graphics g)

public void init( ) public void stop()

public void start() public void destroy()

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.drawString(“Hello”, 20, 20); Hello


g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);

g.drawOval(x, y, width, height);

g.fillOval(x, y, width, height);

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

 2002 Prentice Hall.


 2002 Prentice Hall. All rights reserved. All rights reserved.
Running Applets

– In command prompt, change to demo subdirectory of applet


cd c:\jdk1.3\demo\applets
cd appletDirectoryName
– There will be an HTML file used to execute applet
– Type appletviewer example1.html
• appletviewer loads the html file specified as its command-
line argument
• From the HTML file, determines which applet to load (more
section 3.3)
– Applet will run, Reload and Quit commands under Applet
menu

 2002 Prentice Hall. All rights reserved.


1 // WelcomeApplet.java
2 // A first applet in Java
3 import javax.swing.JApplet; // import class JApplet
4 import java.awt.Graphics; // import class Graphics
5
6 public class WelcomeApplet extends JApplet {
7 public void paint( Graphics g )
8 { super.paint(g);
9 g.drawString( "Welcome to Java Programming!", 25, 25 );
10 }
11 }

1 <html>

2 <applet code="WelcomeApplet.class" width=300 height=30>

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:

String str1 = new String(“Hello there”);

However, as an extra support, Java allows String object to be created


without the use of new, as in:

String str2=”How are you”;


Substring
String objects are represented as a sequence of characters
indexed from 0.
Example: String greeting = “Hello, World!”;
• Java provides two methods for this operation
1. substring(start);
Returns the substring from start to the end of the string
2. substring(start, end);
Returns a substring from start to end but not including the
character at end.
 The first character's index is always 0
 The last character's index is 1 less than the string's length

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;

OUTPUT “Computer Science”


• If one of the operands of the + operator is a string, the other is
automatically converted to string and the two strings are then
concatenated.
String course = “RCSE”;
int code = 12;
String courseCode = course+code
OUTPUT  “RCSE12”
Methods of the String Class
int length() returns the number of
characters in this String
String toUpperCase() returns a new String,
String toLowerCase() equivalent to the Upper/lower
case of this String
boolean equals(s) returns true if s the same as
boolean equalsIgnoreCase(s) this String.
int compareTo(String s) returns +ve number, 0, or -ve
int compareToIngoreCase(s) number if this String is
greater than, equal to or less
than s.
char charAt(index) returns the char in this
String, at the index position.
int indexOf(ch) Returns the index of the first
int lastIndexOf(ch) / last occurrence of ch in
this string, If not fount-1 is
returned
String trim() returns a String, obtained by
removing spaces from the
start and end of this string.

static String valueOf (any Returns a String


primitive type) representation of the
argument
String concat(s) equivalent to + symbol
public class MakePassword {
public static void main(String[] args) {
String firstName = “Computer";
String middleName = "Science";
String lastName = "Engineering";

//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;

String password = initials.toLowerCase()+age;

System.out.println("Your Password ="+password);


} }
String s1 = "Stuart Reges";
String s2 = "Marty Stepp";

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");

String teacher = "Helene";


sayHello(teacher);
}
public static void sayHello(String name) {
System.out.println("Welcome, " + name);
}
}

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

TextField List TextArea

Button

Radio Button
Radio Button Group
Component Class Hierarchy
AWTEvent Container
Panel Applet
Button
Font Window
Canvas Frame

FontMetrics
TextComponent
TextField ScrollPane

Object Color List


TextArea Dialog
Choice
Graphics
Checkbox

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());

add (new Button("NORTH"), BorderLayout.NORTH);

249
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);
}

250
Using a Panel

Panel p = new Panel();


add (p, BorderLayout.SOUTH);
p.add (new Button ("Button 1"));
p.add (new Button ("Button 2"));

251
GridLayout
• The GridLayout manager divides the container up into
a given number of rows and columns:

setLayout(new GridLayout(rows, columns));

• All sections of the grid are equally sized and as large as


possible

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.

Panel aPanel = new Panel();


Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");

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);

CheckboxGroup cbg = new CheckboxGroup();


Checkbox cb1 = new Checkbox("American Express",cbg,false);
Checkbox cb2 = new Checkbox("Visa",cbg,false);
Checkbox cb3 = new Checkbox("Mastercard",cbg,true);
add(cb1,"North");
add(cb2,"Center");
add(cb3,"South");
}

}
256
How to Use Choices?

public class TestChoice extends Frame {


public TestChoice(String title){
super(title);

Choice fruits = new Choice();


fruits.add(“Mango");
fruits.add(“Apple");
fruits.add(“Grapes");
add(fruits);
}
`
257
How to Use TextField & TextArea
public class TestText extends Frame {
public TestText(String title){
super(title);

TextField textField = new TextField(20);


TextArea textArea = new TextArea(5, 20);

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)

class MyCanvas extends Canvas {


public void paint(Graphics g){
g.setColor(Color.blue);
int x1 = 161, (x1,y1)
y1 = 186,
x2 = 181,
y2 = 206; (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){}

public void mouseEntered(MouseEvent e){}

public void mouseExited(MouseEvent e){}

public void mousePressed(MouseEvent e){}

public void mouseReleased(MouseEvent e){}


}
Mouse Event Example-1
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TestMouseListener {
public static void main(String[] args){
Frame f = new Frame("TestMouseListener");
f.setSize(500,500);

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;

class MouseSpy implements MouseListener


{ public void mouseClicked(MouseEvent event)
{ System.out.println("Mouse clicked. x = " + event.getX() +
" y = " + event.getY());
}
public void mouseEntered(MouseEvent event)
{ System.out.println("Mouse entered. x = " + event.getX() +
" y = " + event.getY());
}
public void mouseExited(MouseEvent event)
{ System.out.println("Mouse exited. x = " + event.getX() +
" y = " + event.getY()); 275
}
public void mousePressed(MouseEvent event)
{ System.out.println("Mouse pressed. x = " + event.getX() +
" y = " + event.getY());
}
public void mouseReleased(MouseEvent event)
{ System.out.println("Mouse released. x = " + event.getX() +
" y = " + event.getY());
}
}

public class MouseSpyApplet extends Applet


{ public MouseSpyApplet()
{ MouseSpy listener = new MouseSpy();
addMouseListener(listener);
}
} 276
The WindowAdapter class

public abstract class WindowAdapter implements


WindowListener {

public void windowClosing(WindowEvent e) { }


public void windowClosed(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowActivated(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) { }
}

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
}

You might also like