0% found this document useful (0 votes)
8 views180 pages

Object-Oriented Programming in Java

The document outlines the ITLOJ601 module on Object Oriented Programming using Java, detailing its purpose, learning outcomes, and assessment guidelines. It covers essential Java concepts, including data types, control statements, object-oriented principles, exception handling, and GUI development using AWT and Swing. The module is designed for second-year ICT students at IPRC Musanze for the academic year 2022-2023.

Uploaded by

Jado
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views180 pages

Object-Oriented Programming in Java

The document outlines the ITLOJ601 module on Object Oriented Programming using Java, detailing its purpose, learning outcomes, and assessment guidelines. It covers essential Java concepts, including data types, control statements, object-oriented principles, exception handling, and GUI development using AWT and Swing. The module is designed for second-year ICT students at IPRC Musanze for the academic year 2022-2023.

Uploaded by

Jado
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

DEPARTMENT/SECTOR: ICT

OPTION/SUB-SECTOR: IT

MODULE NAME AND CODE: ITLOJ601


Object Oriented Programming USING JAVA

CREDITS: 12

Level/ Year: 2

Academic year: 2022

Page 1 | 180
Trainer's Name: MUNYANEZA Alphonse
IPRC Musanze, year 2022-2023

Purpose statement
This module describes the skills, knowledge and attitudes required to apply OOP principles that
facilitate effective development of software using Java as the back-end language. After
completion of this module, trainees will be able to use different variables, implement OOP
principles without other problem, handle strings and exceptions without other stackholders as
well as producing GUI using AWT together with Swing technologies.

1. Module assessment guidelines (eg. CBA guidelines governing assignment,

Formative assessment, summative assessment and integrated assessment)

Page 2 | 180
2. Copy right: This module was developed by Mr. MUNYANEZA Alphonse, Assistant
Lecturer in Information Technology department at IPRC MUSANZE. The
copyright reserved to ICT department.

Table of Contents
Page 3 | 180
LEARNING UNIT 1: DESCRIBE JAVA BASIC CONCEPTS AND PREPARE THE ENVIRONEMENT........................8
Introduction............................................................................................................................... 8
1.1.1. Difference between JDK, JRE, and JVM...................................................................................10
First Java Program Hello World Example.................................................................................................12
The requirement for Java Hello World Example...............................................................................12

Learning Outcome: 1.2 Proper use various data types and literals as used in java
programming........................................................................................................................... 13
1.2.1 Java Variables...........................................................................................................................13

[Link] Types of Variables..................................................................................................................14

Example to understand the types of variables in java........................................................................16

Java Variable Example: Add Two Numbers......................................................................................16

Java Variable Example: Widening.....................................................................................................16

Java Variable Example: Narrowing (Typecasting)............................................................................17

1.2.2. Data Types in Java....................................................................................................................17

Java Primitive Data Types....................................................................................................... 17


Boolean Data Type.................................................................................................................. 19
Byte Data Type........................................................................................................................ 20
Short Data Type.......................................................................................................................20
Int Data Type........................................................................................................................... 20
Long Data Type....................................................................................................................... 21
Float Data Type....................................................................................................................... 21
Double Data Type....................................................................................................................21
Char Data Type........................................................................................................................21
Learning Outcomes: 1.3 Proper Use of operators in java.......................................................22
Operators in java.......................................................................................................................................22
Java Operator Precedence........................................................................................................22
Java Unary Operator..........................................................................................................................23

Page 4 | 180
Java Unary Operator Example: ++ and --..........................................................................................23

Java Unary Operator Example 2: ++ and --.......................................................................................24

Java Unary Operator Example: ~ and !..............................................................................................24

Java Arithmetic Operators.................................................................................................................25

Java Arithmetic Operator Example....................................................................................................25

Java Arithmetic Operator Example: Expression................................................................................25

Java Left Shift Operator.....................................................................................................................26

Java Left Shift Operator Example......................................................................................................26

Java Right Shift Operator..................................................................................................................26

Java Right Shift Operator Example...................................................................................................26

Java AND Operator Example: Logical && and Bitwise &...............................................................27

Java AND Operator Example: Logical && vs Bitwise &..................................................................27

Java OR Operator Example: Logical || and Bitwise |.........................................................................28

Java Ternary Operator.......................................................................................................................29

Java Ternary Operator Example........................................................................................................29

Java Assignment Operator.................................................................................................................30

Java Assignment Operator Example..................................................................................................30

Java Assignment Operator Example..................................................................................................30

Java Assignment Operator Example: Adding short...........................................................................31

LEARNING UNIT 2 – Apply control statements..........................................................................................32


Learning Outcomes: 2.1 Apply correctly decision....................................................................32
2.1.1. Java If-else Statement..............................................................................................................32

Java if Statement......................................................................................................................32

Page 5 | 180
Java if-else-if ladder Statement................................................................................................35
Java Nested if statement........................................................................................................37
Java Switch Statement...............................................................................................................................40
Java Switch Statement is fall-through......................................................................................45
Java Switch Statement with String...........................................................................................45
Java Nested Switch Statement................................................................................................. 46
Java Enum in Switch Statement...............................................................................................49
Java Wrapper in Switch Statement......................................................................................50
Learning Outcomes: 2.2 Apply correctly loops........................................................................51
2.2. 1. Java For Loop..........................................................................................................................51

Java Simple For Loop..............................................................................................................52


Java for-each Loop.................................................................................................................. 54
Java While Loop........................................................................................................................................56
Java Infinitive While Loop...................................................................................................... 58
Java do-while Loop...................................................................................................................................59
Java Infinitive do-while Loop..................................................................................................60
Java Break Statement................................................................................................................................61
Java Break Statement with Loop..........................................................................................62
Java Break Statement with Inner Loop...............................................................................63
Java Break Statement in while loop.........................................................................................64
Java Break Statement in do-while loop....................................................................................64
Java Break Statement with Switch.......................................................................................65
Java Continue Statement...........................................................................................................................66
Java Continue Statement Example.......................................................................................66
Java Continue Statement with Inner Loop..........................................................................67
Java Continue Statement in while loop................................................................................68
Learning Outcomes: 2.3 Apply correctly jump statements......................................................70
Java Break Statement...............................................................................................................70
Java Continue Jumping Statement...........................................................................................71
Page 6 | 180
Java Return Jumping Statement...............................................................................................72
Java Comments.........................................................................................................................................73
Types of Java Comments.......................................................................................................73
1) Java Single Line Comment..................................................................................................73
2) Java Multi Line Comment................................................................................................74
3) Java Documentation Comment........................................................................................75
LEARNING UNIT 3– APPLY OBJECT ORIENTED PRINCIPALS......................................................75
LEARNING UNIT 3– APPLY OBJECT ORIENTED PRINCIPALS......................................................76
3.1 Proper use of class and object...........................................................................................76
3.2 Proper use of methodsMethod..........................................................................................81
3.4 Correct application of constructors...................................................................................88
3.3 Correct implementation of static.......................................................................................92
3.5 Apply Inheritance.............................................................................................................101
3.6 Apply Polymorphism........................................................................................................109
3.7 Apply encapsulation, package and access protections....................................................114
3.8 Apply Abstraction.............................................................................................................117
LEARNING UNIT 4 – PROCESS STRING AND ARRAYS.................................................................120
Learning Outcome: 4.1 Apply single dimension....................................................................121
Advantages.....................................................................................................................................121

Disadvantages................................................................................................................................122

Types of Array in java.....................................................................................................................122

Single Dimensional Array in Java..........................................................................................122


Example of Java Array....................................................................................................................122

Declaration, Instantiation and Initialization of Java Array.............................................123


For-each Loop for Java Array................................................................................................124
Passing Array to a Method in Java.........................................................................................125
Anonymous Array in Java.................................................................................................. 125
Returning Array from the Method.....................................................................................126
Page 7 | 180
ArrayIndexOutOfBoundsException...................................................................................127
Learning Outcome: 4.2 Apply Multiple dimension................................................................128
Example of Multidimensional Java Array...................................................................................128

Addition of 2 Matrices in Java............................................................................................129


Multiplication of 2 Matrices in Java...................................................................................130
Learning Outcome: 4.3 Correct reading creation of a string..................................................132
java String Methods...............................................................................................................132
LEARNING UNIT 5 – HANDLE EXCEPTIONS...............................................................................................136
Learning Outcomes: 5.1 Proper throwing of exception to avoid risks at runtime..................136
Error vs Exception........................................................................................................................137

Exception Hierarchy.......................................................................................................................137

Learning Outcomes: 5.2 Correct use of try statement to separate the logic that might throw
an exception from the logic to handle that exception.............................................................138
Java try and catch...................................................................................................................139
Learning Outcomes: 5.3 Correct identification of common exceptions correct creation of
custom Exceptions.................................................................................................................139
Types of Exceptions.......................................................................................................................139

LEARNING UNIT 6 – DEVELOP GUI USING AWT..........................................................................140


LEARNING UNIT 7 – Program GUI with Swing...................................................................................141
7.1.1. Swing Basics..........................................................................................................................141

Learning Outcome: 7.2 Prepare appropriately the working...................................................142


[Link] basic.......................................................................................................................142

Learning Outcome: 7.3 Proper Use Swing Controls...............................................................147


LEARNING UNIT 8 – JDBC.........................................................................................................................147
Learning Outcomes: 8.1 Proper connection to Mysql Database............................................147
8.1.1. Accessing database with JDBC (Java database connectivity)......................................148
Learning Outcome: 8.2 Proper application of JDBC CRUD.....................................................150
8.2.1. Creating a sample MySQL database............................................................................150
Page 8 | 180
8.2.2. Connecting to the database...........................................................................................151
JDBC Execute INSERT Statement Example.........................................................................152
JDBC Execute SELECT Statement Example.........................................................................152
JDBC Executing UPDATE Statement Example....................................................................153
JDBC Execute DELETE Statement Example........................................................................153
Learning Outcome :8.3 Roper application of Prepared Statement interface...........................154

LEARNING UNIT 1: DESCRIBE JAVA BASIC


CONCEPTS AND PREPARE THE ENVIRONEMENT
Learning Outcomes:
1.1 Describe and install properly java
platform components
1.2 Proper use various data types and
literals as used in java programming.

Page 9 | 180
1.3 Proper Use of operators in java.

Introduction
Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of java
starts with Green Team. Java team members (also known as Green Team), initiated this project
to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was
suited for internet programming. Later, Java technology was incorporated by Netscape. The
principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted
and Dynamic". Currently, Java is used in internet programming, mobile devices, games, e-
business solutions, etc. There are given the significant points that describe the history of Java.
Java IDE
A Java IDE (Integrated Development Environment) is a software application which enables users
to more easily write and debug Java programs. Many IDEs provide features like syntax
highlighting and code completion, which help the user to code more easily.

Netbean

NetBeans is an open source Integrated Development Environment written in Java and is one of
IDR Solutions favourite IDE’s for Java Coding.

The NetBeans IDE supports development of all Java application types (Java SE, JavaFX, Java
ME, web, EJB and mobile applications) standard out of the box. NetBeans is modular in design
meaning it can be extended by third party developers who can create plugins for NetBeans to
enhance functionality (Our PDF Plugin for NetBeans is a good example).

Page 10 | 180
The NetBeans IDE is can be used to develop in Java, but also supports other languages, in
particular PHP, C/C++, and HTML5.

NetBeans features are an Ant-based project system, support for Maven, refactoring, version
control (supporting CVS, Subversion, Git, Mercurial and Clearcase) and is also released under a
dual license consisting of the Common Development and Distribution License (CDDL) v1.0 and
the GNU General Public License (GPL) v2.

NetBeans is cross-platform and runs on Microsoft Windows, Mac OS X, Linux, Solaris and
other platforms supporting a compatible JVM.

Eclipse

Eclipse is another free Java IDE for developers and programmers and it is mostly written in Java.
Eclipse lets you create various cross platform Java applications for use on mobile, web, desktop
and enterprise domains.

Its main features include a Windows Builder, integration with Maven, Mylyn, XML editor, Git
client, CVS client, PyDev, and it contains a base workspace with an extensible plug-in system
for customizing the IDE to suit your needs. Through plugins you can develop applications in
other programming languages some of which include , C, C++, JavaScript,, Perl, PHP, Prolog,
Python, R, Ruby (including Ruby on Rails framework), to name just a few.

Eclipse is available under an Eclipse Public License and is available on Windows, Mac OS X
and Linux.

Other IDEs

1. Jcreator
2. JBuilder

Page 11 | 180
3. DrJava

4. JDeveloper

Learning Outcome: 1.1. Describe and install properly java

1.1.1. Difference between JDK, JRE, and JVM

We must understand the differences between JDK, JRE, and JVM before proceeding further
to java. See the brief overview of JVM here.

Firstly, let's see the differences between the JDK, JRE, and JVM.

JVM (Java Virtual Machine) is an abstract (intangible) machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime environment in
which Java byte code can be executed. It can also run those programs which are written in other
languages and compiled to Java byte code.

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java applications.
It is used to provide the runtime environment. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.

Page 12 | 180
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.

Page 13 | 180
First Java Program Hello World Example

We can write a simple hello java program easily after installing the JDK.

To create a simple java program, you need to create a class that contains the main method. Let's
understand the requirement first.

The requirement for Java Hello World Example

For executing any java program, you need to

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory.
o Create the java program
o Compile and run the java program

Page 14 | 180
package iprc_musanze;
public class IPRC_Musanze
{
public static void main(String[] args)
{
[Link]("Hello World!");
}}

Learning Outcome: 1.2 Proper use various data types and


literals as used in java programming.

1.2.1 Java Variables

A variable is a container which holds the value while the java program is executed. A variable is
assigned with a data type.

Page 15 | 180
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

There are two types of data types in java: primitive and non-primitive.

Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.

int data=50;//Here data is variable

[Link] Types of Variables

There are three types of variables in java:

o local variable
o instance variable
o static variable

Page 16 | 180
1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among
instances.

Page 17 | 180
3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in the memory.

Example to understand the types of variables in java

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

Java Variable Example: Add Two Numbers

class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
}}

Output:

20

Page 18 | 180
Java Variable Example: Widening

class Simple{
public static void main(String[] args){
int a=10;
float f=a;
[Link](a);
[Link](f);
}}

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)

class Simple{
public static void main(String[] args){
float f=10.5;
//int a=f;//Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}}

Output:

10.5
10

Page 19 | 180
1.2.2. Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared before
its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

 boolean data type


 byte data type
 char data type
 short data type

o int data type


o long data type
o float data type
o double data type

Page 20 | 180
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

Page 21 | 180
long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.

Example: byte a = 10, byte b = -20

Page 22 | 180
Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.

Example: short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L


Page 23 | 180
Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0d.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'

Learning Outcomes: 1.3 Proper Use of operators in java.

Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

Page 24 | 180
There are many types of operators in java which are given below:

 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift <<>>>>>

Relational comparison <><= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

Page 25 | 180
bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --

class OperatorExample{
public static void main(String args[]){
int x=10;
[Link](x++);//10 (11)
[Link](++x);//12
[Link](x--);//12 (11)
[Link](--x);//10
}}

Output:

Page 26 | 180
10

12

12

10

Java Unary Operator Example 2: ++ and --

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
[Link](a++ + ++a);//10+12=22
[Link](b++ + b++);//10+11=21
}}

Output:

22

21

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.

Java Arithmetic Operator Example

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;

Page 27 | 180
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression

class OperatorExample{
public static void main(String args[]){
[Link](10*10/5+3-1*4/2);
}}
Output:
21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example

class OperatorExample{
public static void main(String args[]){
Page 28 | 180
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240
}}

Output:

40

80

80

240

Java Right Shift Operator

The Java right shift operator >> is used to move left operands value to right by the number of
bits specified by the right operand.

Java Right Shift Operator Example

class OperatorExample{
public static void main(String args[]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2

Page 29 | 180
Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check second condition if first condition is false. It checks
second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
[Link](a<b&&a<c);//false && true = false
[Link](a<b&a<c);//false & true = false
}}

Output:

false

false

Java AND Operator Example: Logical && vs Bitwise &

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
[Link](a<b&&a++<c);//false && true = false
[Link](a);//10 because second condition is not checked
[Link](a<b&a++<c);//false && true = false
Page 30 | 180
[Link](a);//11 because second condition is checked
}}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
[Link](a>b||a<c);//true || true = true
[Link](a>b|a<c);//true | true = true
//|| vs |
[Link](a>b||a++<c);//true || true = true
[Link](a);//10 because second condition is not checked
[Link](a>b|a++<c);//true | true = true
[Link](a);//11 because second condition is checked
}}
Page 31 | 180
Output:
true
true
true
10
true
11

Java Ternary Operator

Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in
java programming. it is the only conditional operator which takes three operands.

Java Ternary Operator Example

class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Output:

Another Example:

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
Page 32 | 180
[Link](min);
}}

Output:

Java Assignment Operator

Java assignment operator is one of the most common operator. It is used to assign the value on
its right to the operand on its left.

Java Assignment Operator Example

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
[Link](a);
[Link](b);
}}

Output:

14
16

Java Assignment Operator Example

class OperatorExample{

Page 33 | 180
public static void main(String[] args){
int a=10;
a+=3;//10+3
[Link](a);
a-=4;//13-4
[Link](a);
a*=2;//9*2
[Link](a);
a/=2;//18/2
[Link](a);
}}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short

class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
[Link](a);
}}

Output:

Page 34 | 180
Compile time error

After type cast:

class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
[Link](a);
}}

Output:

20

LEARNING UNIT 2 – Apply control statements


Learning Outcomes:

2.1 Apply correctly decision making statements.

2.2 Apply correctly loops

2.3 Apply correctly jump statements

Page 35 | 180
Learning Outcomes: 2.1 Apply correctly decision
2.1.1. Java If-else Statement

The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.

 if statement
 if-else statement
 if-else-if ladder
 nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition is true.

Syntax:

if(condition){
//code to be executed
}

Page 36 | 180
Example:

//Java Program to demonstate the use of if statement.


public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
[Link]("Age is greater than 18");
}
}
}

Output:
Page 37 | 180
Age is greater than 18

Java if-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.

Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}

Example:

//A Java Program to demonstrate the use of if-else statement.


//It is a program of odd and even number.

Page 38 | 180
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
[Link]("even number");
}else{
[Link]("odd number");
}
}
}

Output:

odd number

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true

Page 39 | 180
}
...
else{
//code to be executed if all the conditions are false
}

Example:

//Java Program to demonstrate the use of If else-if ladder.

Page 40 | 180
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;

if(marks<50){
[Link]("fail");
}
else if(marks>=50 && marks<60){
[Link]("D grade");
}
else if(marks>=60 && marks<70){
[Link]("C grade");
}
else if(marks>=70 && marks<80){
[Link]("B grade");
}
else if(marks>=80 && marks<90){
[Link]("A grade");
}else if(marks>=90 && marks<100){
[Link]("A+ grade");
}else{
[Link]("Invalid!");
}
}
}
Output:
C grade

Java Nested if statement

The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.

Syntax:
Page 41 | 180
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}

Page 42 | 180
Example:

Page 43 | 180
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
[Link]("You are eligible to donate blood");
}
}
}}

Output:

You are eligible to donate blood

Example 2:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){

Page 44 | 180
[Link]("You are eligible to donate blood");
} else{
[Link]("You are not eligible to donate blood");
}
} else{
[Link]("Age must be greater than 18");
}
} }

Output:

You are not eligible to donate blood

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement. The switch statement works with byte, short, int, long, enum types, String and
some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the
switch statement.

In other words, the switch statement tests the equality of a variable against multiple values.

Points to Remember

o There can be one or N number of case values for a switch expression.


o The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-time error.
o The Java switch expression must be of byte, short, int, long (with its Wrapper type),
enums and string.
Page 45 | 180
o Each case statement can have a break statement which is optional. When control reaches
to the break statement, it jumps the control after the switch expression. If a break
statement is not found, it executes the next case.
o The case value can have a default label which is optional.

Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Page 46 | 180
Example:

public class SwitchExample {


public static void main(String[] args) {

Page 47 | 180
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
//Default case statement
default:[Link]("Not in 10, 20 or 30");
}
}
}

Output:

20

Finding Month Example:

//Java Program to demonstrate the example of Switch statement


//where we are printing month name for the given number
public class SwitchMonthExample {
public static void main(String[] args) {
//Specifying month number
int month=7;

Page 48 | 180
String monthString="";
//Switch statement
switch(month){
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
Page 49 | 180
default:[Link]("Invalid Month!");
}
//Printing month of the given number
[Link](monthString);
}
}

Output:

7 - July

Java Switch Statement is fall-through

The Java switch statement is fall-through. It means it executes all statements after the first match
if a break statement is not present.

Example:

//Java Switch Example where we are omitting the


//break statement
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: [Link]("10");
case 20: [Link]("20");
case 30: [Link]("30");
default:[Link]("Not in 10, 20 or 30");
Page 50 | 180
}
}
}

Output:

20
30
Not in 10, 20 or 30

Java Switch Statement with String

Java allows us to use strings in switch expression since Java SE 7. The case statement should be
string literal.

Example:

//Java Program to demonstrate the use of Java Switch


//statement with String
public class SwitchStringExample {
public static void main(String[] args) {
//Declaring String variable
String levelString="Expert";
int level=0;
//Using String in Switch expression
switch(levelString){
//Using String Literal in Switch case
case "Beginner": level=1;
break;
case "Intermediate": level=2;
break;
Page 51 | 180
case "Expert": level=3;
break;
default: level=0;
break;
}
[Link]("Your Level is: "+level);
}
}

Output:

Your Level is: 3

Java Nested Switch Statement

We can use switch statement inside other switch statement in Java. It is known as nested switch
statement.

Example:

//Java Program to demonstrate the use of Java Nested Switch


public class NestedSwitchExample {
public static void main(String args[])
{
//C - CSE, E - ECE, M - Mechanical
char branch = 'C';
int collegeYear = 4;
switch( collegeYear )
{
case 1:
Page 52 | 180
[Link]("English, Maths, Science");
break;
case 2:
switch( branch )
{
case 'C':
[Link]("Operating System, Java, Data Structure");
break;
case 'E':
[Link]("Micro processors, Logic switching theory");
break;
case 'M':
[Link]("Drawing, Manufacturing Machines");
break;
}
break;
case 3:
switch( branch )
{
case 'C':
[Link]("Computer Organization, MultiMedia");
break;
case 'E':
[Link]("Fundamentals of Logic Design, Microelectronics");
break;
case 'M':
[Link]("Internal Combustion Engines, Mechanical Vibration");
break;
Page 53 | 180
}
break;
case 4:
switch( branch )
{
case 'C':
[Link]("Data Communication and Networks, MultiMedia");
break;
case 'E':
[Link]("Embedded System, Image Processing");
break;
case 'M':
[Link]("Production Technology, Thermal Engineering");
break;
}
break;
}
}
}

Output:

Data Communication and Networks, MultiMedia

Java Wrapper in Switch Statement

Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

Example:

Page 54 | 180
//Java Program to demonstrate the use of Wrapper class
//in switch statement
public class WrapperInSwitchCaseExample {
public static void main(String args[])
{
Integer age = 18;
switch (age)
{
case (16):
[Link]("You are under 18.");
break;
case (18):
[Link]("You are eligible for vote.");
break;
case (65):
[Link]("You are senior citizen.");
break;
default:
[Link]("Please give the valid age.");
break;
}
}
}

Output:

You are eligible for vote.

Page 55 | 180
Learning Outcomes: 2.2 Apply correctly loops
2.2. 1. Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.

There are three types of for loops in java.

 Simple For Loop


 For-each or Enhanced For Loop
 Labeled For Loop

Java Simple For Loop

A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:

1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is an
optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false. It must return boolean value
either true or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is
false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.

Syntax:

Page 56 | 180
for(initialization;condition;incr/decr){
//statement or code to be executed
}

Flowchart:

Example:

Page 57 | 180
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
[Link](i);
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Java for-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

Page 58 | 180
for(Type var:array){
//code to be executed
}

Example:

//Java For-each loop example which prints the


//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
[Link](i);
}
}
}

Output:
12
23
44
56
78
Java Infinitive For Loop

If you use two semicolons;; in the for loop, it will be infinitive for loop.

Syntax:

for(; ;){

Page 59 | 180
//code to be executed
}

Example:

//Java program to demonstrate the use of infinite for loop


//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
[Link]("infinitive loop");
}
}
}

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Java While Loop

The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.

Page 60 | 180
Syntax:

while(condition){
//code to be executed
}

Page 61 | 180
Example:

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}

Output:

1
Page 62 | 180
2
3
4
5
6
7
8
9
10

Java Infinitive While Loop

If you pass true in the while loop, it will be infinitive while loop.

Syntax:

while(true){
//code to be executed
}

Example:

public class WhileExample2 {


public static void main(String[] args) {
while(true){
[Link]("infinitive while loop");
}
}
}

Output:

infinitive while loop


Page 63 | 180
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Java do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop body.

Syntax:

do{
//code to be executed
}while(condition);

Page 64 | 180
Example:

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=10);
}
}

Output:

Page 65 | 180
2
3
4
5
6
7
8
9
10

Java Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

Syntax:

do{
//code to be executed
}while(true);

Example:

public class DoWhileExample2 {


public static void main(String[] args) {
do{
[Link]("infinitive do while loop");
}while(true);
}
}

Output:

infinitive do while loop


Page 66 | 180
infinitive do while loop
infinitive do while loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Java Break Statement

When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.

The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.

We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.

Syntax:

jump-statement;
break;

Page 67 | 180
Java Break Statement with Loop

Example:

//Java Program to demonstrate the use of break statement


//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
[Link](i);

Page 68 | 180
}
}
}

Output:
1
2
3
4

Java Break Statement with Inner Loop

It breaks inner loop only if you use break statement inside the inner loop.

Example:

//Java Program to illustrate the use of break statement


//inside an inner loop
public class BreakExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement inside the inner loop
break;
}
[Link](i+" "+j);
}
}

Page 69 | 180
}
}

Output:

11
12
13
21
31
32
33

Java Break Statement in while loop

Example:

//Java Program to demonstrate the use of break statement


//inside the while loop.
public class BreakWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
[Link](i);
i++;

Page 70 | 180
}
}
}

Output:

1
2
3
4

Java Break Statement in do-while loop

Example:

//Java Program to demonstrate the use of break statement


//inside the Java do-while loop.
public class BreakDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
[Link](i);
i++;
}while(i<=10);
Page 71 | 180
}
}

Output:

1
2
3
4

Java Break Statement with Switch

To understand the example of break with switch statement, please visit here: Java Switch
Statement.

Java Continue Statement

The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately. It can be used with for loop or while loop.

The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.

We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.

Syntax:

jump-statement;
continue;

Page 72 | 180
Java Continue Statement Example

Example:

//Java Program to demonstrate the use of continue statement


//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
[Link](i);
}
}
}

Output:

1
2
3
4
6
7
8
9
10
Page 73 | 180
As you can see in the above output, 5 is not printed on the console. It is because the loop is
continued when it reaches to 5.

Java Continue Statement with Inner Loop

It continues inner loop only if you use the continue statement inside the inner loop.

Example:

//Java Program to illustrate the use of continue statement


//inside an inner loop
public class ContinueExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using continue statement inside inner loop
continue;
}
[Link](i+" "+j);
}
}
}
}

Output:

11
Page 74 | 180
12
13
21
23
31
32
33

Java Continue Statement in while loop

Example:

//Java Program to demonstrate the use of continue statement


//inside the while loop.
public class ContinueWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using continue statement
i++;
continue;//it will skip the rest statement
}
[Link](i);
i++;
}
}
}

Output:
Page 75 | 180
1
2
3
4
6
7
8
9
10
Java Continue Statement in do-while loop

Example:

//Java Program to demonstrate the use of continue statement


//inside the Java do-while loop.
public class ContinueDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using continue statement
i++;
continue;//it will skip the rest statement
}
[Link](i);
i++;
}while(i<=10);
}
}

Page 76 | 180
Output:

1
2
3
4
6
7
8
9

Learning Outcomes: 2.3 Apply correctly jump statements

Java Break Statement

We can use break statement in the following cases.

Inside the switch case to come out of the switch block.

Within the loops to break the loop execution based on some condition.

Inside labelled blocks to break that block execution based on some condition.

class Test
{
public static void main(String[] args)
{
for(int j=0; j<10; j++)
{
if(j==5)
{
break;
}
[Link](j);

Page 77 | 180
}
[Link]("outside of for loop");
}
}
Output:-

0
1
2
3
4
outside of for loop

Java Continue Jumping Statement

This statement is used only within looping statements. When the continue statement is
encountered, then it skip the current iteration and the next iteration starts. The remaining
statements in the loop are skipped. The execution starts from the top of loop again. We can use
continue statement to skip current iteration and continue the next iteration inside loops.

class Test
{
public static void main(String[] args)
{
for(int j=1; j<=100; j++)
{
if(j%2==0)
{
continue;
}
[Link](j);
}
}
}
Output:-
Page 78 | 180
1
3
5
.
.
99

Java Return Jumping Statement

The return statement is mainly used in methods in order to terminate a method in between and
return back to the caller method. It is an optional statement. That is, even if a method doesn't
include a return statement, control returns back to the caller method after execution of the
method. Return statement may or may not return parameters to the caller method.

class Test
{
public static void main(String[] args)
{
Test t = new Test();
int sum = [Link](10,20); //addition() method return integer value
[Link]("Sum = "+sum);
[Link]("Devavrat"); //show() method does not return any value
}
int addition(int a,int b)
{
return a+b;
}
void show(String name)
{
[Link]("Welcome "+name);
return; // not returning anything, it is optional
}
}
Output:-
Page 79 | 180
Sum = 30
Welcome Devavrat

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

Page 80 | 180
1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

//This is single line comment

Example:

public class CommentExample1 {


public static void main(String[] args) {
int i=10;//Here, i is a variable
Page 81 | 180
[Link](i);
}
}

Output:

10

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/* This is multi line comment */

Example:

public class CommentExample2 {


public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
[Link](i);
}
}

Output:

10

Page 82 | 180
3) Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API,
you need to use javadoc tool.

Syntax:

/**
This is documentation comment */

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}

Page 83 | 180
LEARNING UNIT 3– APPLY OBJECT ORIENTED PRINCIPALS
Learning Outcomes:
3.1 Proper use of class and object
3.2 Proper use of methods
3.3 Correct implementation of static.
3.4 Correct application of constructors
3.5 Apply Inheritance
3.6 Apply Polymorphism
3.7 Apply encapsulation, package and access protections
3.8 Apply Abstraction

3.1 Proper use of class and object


Introduction

A class is a group of objects that has common properties. It is a template or


blueprint from which objects are created.

A class in java can contain:

 data member
 method
 constructor
 block
 class and interface

Syntax
1. class <class_name>{

Page 84 | 180
2. data member;
3. method;
4. }
Object

An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tengible and intengible).
The example of integible object is banking system.

An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. But,it is used internally
by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as
its state. It is used to write, so writing is its behavior.

Page 85 | 180
Simple example of class and object

In this example, we have created a Student class that have two data members id
and name. We are creating the object of the Student class by new keyword and
printing the objects value.

publicclass Student1 {
intid;//data member (also instance variable)
String name;//data member(also instance variable)
publicstaticvoid main(String[] args) {
Student1 s1=new Student1();//creating an object of Student
[Link]([Link]);
}
}

Output

Page 86 | 180
0

Instance variable in java

A variable that is created inside the class but outside the method, is known as
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when object(instance) is created. That is why, it is known as
instance variable.

newkeyword

The new keyword is used to allocate memory at runtime.

Example of object and class that maintain the record of students

In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method on it. Here, we are
displaying the state (data) of the objects by invoking the displayInformation method.

publicclass Student2 {
introllno;
String name;
void insertRecord(intr, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+"
"+name);}//method
publicstaticvoid main(String[] args) {
Student2 s1=new Student2();
Student2 s2=new Student2();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
Page 87 | 180
}

Output

111 Karan
222 Aryan

As you see in the above figure, object gets the memory in Heap area and
reference variable refers to the object allocated in the Heap memory area. Here,
s1 and s2 both are reference variables that refer to the objects allocated in
memory.

Another example of class and object

There is given another example that maintains the records of Rectangle class. Its
explanation is same as in the above Student class example.

publicclass Rectangle {
Page 88 | 180
intlength;
intwidth;
void insert(intl,intw){
length=l;
width=w;
}
void calculateArea(){[Link](length*width);}
publicstaticvoid main(String[] args) {
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
[Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}

Output

55
45

Creating multiple objects of by one type only

We can create multiple objects by one type only as we do in case of primitives.

Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Example

publicclass Rectangle {
intlength;
intwidth;
void insert(intl,intw){
length=l;
width=w;

Page 89 | 180
}
void calculateArea(){[Link](length*width);}
publicstaticvoid main(String[] args) {
Rectangle r1=new Rectangle(),r2=new Rectangle();
two objects
[Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}
}

Output

55
45

3.2 Proper use of Methods


Methods are functions defined inside classes that operate on instances of those
classes.
Methods don’t always affect only a single object; objects communicate with each
other using methods as well.
Think of a method as a subprogram that acts on data and often returns a value.
A class or object can call methods in another class or object to communicate
changes in the environment or to ask that object to change its state.
Method declaration

Here is an example of a typical method declaration:

public double calculateAnswer(double wingSpan, int numberOfEngines,


double length, double grossTons) {

Page 90 | 180
//do the calculation here
}

The only required elements of a method declaration are the method's return type,
name, a pair of parentheses, (), and a body between braces, {}.

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}

More generally, method declarations have six components, in order:

1. Modifiers-such as public, private, and others you will learn about later.
2. The return type-the data type of the value returned by the method, or void
if the method does not return a value.
3. The method name-the rules for field names apply to method names as
well, but the convention is a little different.
4. The parameter list in parenthesis-a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty parentheses.
5. The method body, enclosed between braces-the method's code, including
the declaration of local variables, goes here.

Modifiers, return types, and parameters will be discussed later in this lesson.
Exceptions are discussed in a later lesson.

Naming a method

Page 91 | 180
Although a method name can be any legal identifier, code conventions restrict
method names. By convention, method names should be a verb in lowercase or a
multi-word name that begins with a verb in lowercase, followed by adjectives,
nouns, etc. In multi-word names, the first letter of each of the second and
following words should be capitalized. Here are some examples:

Run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

Typically, a method has a unique name within its class. However, a method
might have the same name as other methods due to method overloading.

Method calling

For using a method, it should be called. There are two ways in which a method is
called i.e., method returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when:

 The return statement is executed.

Page 92 | 180
 It reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Let’s consider an


example

[Link]("This is [Link]!");

The method returning value can be understood by the following example

int result = sum(6,9);

Following is the example to demonstrate how to define a method and how to call
it

publicclass ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
[Link]("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
Public static int minFunction(intn1, intn2) {
Int min;
if (n1>n2)
min = n2;
else
min = n1;
return min;
}
}

Output

Minimum Value = 6

Void keyword
Page 93 | 180
The void keyword allows us to create methods which do not return a value. Here,
in the following example we're considering a void method methodRankPoints.
This method is a void method, which does not return any value. Call to a void
method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement
which ends with a semicolon as shown in the following example.

Example

publicclass ExampleVoid {
publicstaticvoid main(String[] args) {
methodRankPoints(255.7);
}
publicstaticvoid methodRankPoints(doublepoints) {
if (points>= 202.5) {
[Link]("Rank:A1");
}
elseif (points>= 122.4) {
[Link]("Rank:A2");
}
else {
[Link]("Rank:A3");
}
}
}

Output

Rank:A1

Passing parameters by value

While working under calling process, arguments is to be passed. These should be


in the same order as their respective parameters in the method specification.
Parameters can be passed by value or by reference.

Page 94 | 180
Passing Parameters by Value means calling a method with a parameter. Through
this, the argument value is passed to the parameter.

Example

The following program shows an example of passing parameter by value. The


values of the arguments remains the same even after the method invocation.

publicclass swappingExample {
publicstaticvoid main(String[] args) {
int a = 30;
int b = 45;
[Link]("Before swapping, a = " + a + " and b = "
+ b);
// Invoke the swap method
swapFunction(a, b);
[Link]("\n**Now, Before and After swapping values
will be same here**:");
[Link]("After swapping, a = " + a + " and b is "
b);
}
publicstaticvoid swapFunction(int a, int b) {
[Link]("Before swapping(Inside), a = " +
" + b);
// Swap n1 with n2
intc = a;
a = b;
b = c;
[Link]("After swapping(Inside), a = " + a
+ b);
}
}

Output

Before swapping, a = 30 and b = 45


Before swapping(Inside), a = 30 b = 45
Page 95 | 180
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45

Overloading method

If a class have multiple methods by same name but different parameters, it is


known as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b (int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behavior of the method because
its name differs. So, we perform method overloading to figure out the program
quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Example of Method Overloading by changing the no. of arguments

Page 96 | 180
In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition of
three numbers.

publicclass Calculation {
void sum(inta,intb){[Link](a+b);}
void sum(inta,intb,intc){[Link](a+b+c);}
publicstaticvoid main(String[] args) {
Calculation obj=new Calculation();
[Link](10,10,10);
[Link](20,20);
}

Output
30
40
2) Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data
type. The first sum method receives two integer arguments and second sum
method receives two double arguments.

publicclass Calculation2 {
void sum(inta,intb){[Link](a+b);}
void sum(doublea,doubleb){[Link](a+b);}
publicstaticvoid main(String[] args) {
Calculation2 obj=new Calculation2();
[Link](10.5,10.5);
[Link](20,20);
}

Page 97 | 180
}
Output
21.0
40

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a
class by method overloading. Let's see the simple example:

publicclass Overloading1 {
public static void main(int a){
[Link](a);
}
public static void main(String[] args) {
[Link]("main() method invoked");
main(10);
}
}

Output
main() method invoked
10

3.4 Correct application of constructors


Constructor in java is a special type of method that is used to initialize the
object.

Java constructor is invoked at the time of object creation. It constructs the values

Page 98 | 180
i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor

<class_name>(){}

Example of default constructor


Page 99 | 180
In this example, we are creating the no-arg constructor in the Bike class. It will
be invoked at the time of object creation.

publicclass Bike1 {
Bike1(){[Link]("Bike is created");}
publicstaticvoid main(String[] args) {
Bike1 b=new Bike1();
}

}
Output
Bike is created

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct


objects.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

publicclass Student4 {
Page 100 | 180
intid;
String name;
Student4(inti,String n){
id = i;
name = n;
}
void display(){[Link](id+" "+name);}
publicstaticvoid main(String[] args) {
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
[Link]();
[Link]();
}
}

Output
111 Karan
222 Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists. The compiler differentiates
these constructors by taking into account the number of parameters in the list and
their type.

Example of Constructor Overloading

publicclass Student5 {
intid;
String name;
intage;
Student5(inti,String n){
id = i;
name = n;
}
Student5(inti,String n,inta){
id = i;
name = n;
age=a;
Page 101 | 180
}
void display(){[Link](id+" "+name+" "+age);}
publicstaticvoid main(String[] args) {
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}

Output
111 Karan 0
222 Aryan 25
Difference between constructor and method in java

There are many differences between constructors and methods. They are given
below.

Java Constructor Java Method


Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.
Constructor name must be same as the class name. Method name may or may not be
same as class name.

3.5 Correct implementation of static.

Page 102 | 180


Static keyword

The static keyword in java is used for memory management mainly. We can
apply java static keyword with variables, methods, blocks and nested class. The
static keyword belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

Java static variable

If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
 The static variable gets memory only once in class area at the time of
class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Example

package lesson7;
publicclass Student3 {
Page 103 | 180
introllno;
String name;
static String college ="ITS";
Student3(intr,String n){
rollno = r;
name = n;
}
void display (){[Link](rollno+" "+name+" "+college
publicstaticvoidmain(String[] args) {
Student3 s1 = new Student3(111,"Karan");
Student3 s2 = new Student3(222,"Aryan");
[Link]();
[Link]();
}
}

Output

111 Karan ITS


222 Aryan ITS

Page 104 | 180


Java static method

If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than object of a class.


 A static method can be invoked without the need for creating an instance
of a class.
 A static method can access static data member and can change the value
of it.

Page 105 | 180


Example

publicclass Student5 {
introllno;
String name;
static String college = "ITS";
staticvoid change(){
college = "BBDIT";
}
Student5(intr, String n){
rollno = r;
name = n;
}
void display (){[Link](rollno+" "+name+" "+college
publicstaticvoid main(String[] args) {
[Link]();
Student5 s1 = new Student5 (111,"Karan");
Student5 s2 = new Student5 (222,"Aryan");
Student5 s3 = new Student5 (333,"Sonoo");
[Link]();
[Link]();
[Link]();
}

Output

111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT

Restriction of static method

There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method directly.

Page 106 | 180


2. this and super cannot be used in static context.

Example

publicclass A {
inta=40;//non static
publicstaticvoid main(String[] args) {
[Link](a);
}
}

Output

Exception in thread "main" [Link]: Unresolved compilation


problem:
Cannot make a static reference to the non-static field

Static block

 Is used to initialize the static data member.


 It is executed before main method at the time of classloading.

Example

publicclass A2 {
static{[Link]("static block is invoked");}
publicstaticvoid main(String[] args) {
[Link]("Hello main");
}

Output

Page 107 | 180


static block is invoked
Hello main

Access modifiers in java

There are two types of modifiers in java: access modifiers and non-access
modifiers.

The access modifiers in java specifies accessibility (scope) of a data member,


method, constructor or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized,


native, volatile, transient etc. Here, we will learn access modifiers.

Private access modifier

The private access modifier is accessible only within class.

Example

In this example, we have created two classes A3 and Simple. A class contains
private data member and private method. We are accessing these private members
from outside the class, so there is compile time error.

class A3{

Page 108 | 180


privateintdata=40;
privatevoid msg(){[Link]("Hello java");}
}
publicclass Simple {
publicstaticvoid main(String[] args) {
A3 obj=new A3();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}

Error

Exception in thread "main" [Link]: Unresolved compilation


problems:
The field [Link] is not visible
The method msg() from the type A3 is not visible

The role of private modifier

If you make any class constructor private, you cannot create the instance of that
class from outside the class. For example:

class A4{
private A4(){}//private constructor
void msg(){[Link]("Hello java");}
}
publicclass Simple2 {

publicstaticvoid main(String[] args) {


A4 obj=new A4();//Compile Time Error
}

Page 109 | 180


Default access modifier

If you don't use any modifier, it is treated as default by default. The default
modifier is accessible only within package.

Example

In this example, we have created two packages pack and mypack. We are
accessing the A5 class from outside its package, since A5 class is not public, so it
cannot be accessed from outside the package.

package mypack;
import pack.*;
publicclass B {
publicstaticvoid main(String[] args) {
A5obj=newA5();//compile time error
[Link]();//compile time error
}

Explanation

In the above example, the scope of class A5 and its method displayName() is
default so it cannot be accessed from outside the package.

Protected access modifier

The protected access modifier is accessible within package and outside the
package but through inheritance only.

The protected access modifier can be applied on the data member, method and

Page 110 | 180


constructor. It can't be applied on the class.

Example

In this example, we have created the two packages pack and mypack. The A6
class of pack package is public, so can be accessed from outside the package.
But displayName() method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.

package pack;
publicclass A6 {
String className="CLASS A";
protected String displayName()
{
returnclassName;
}

package mypack;
import pack.*;
publicclass B2 {
publicstaticvoid main(String[] args) {
A6 obj=new A6();
[Link]([Link]());
}
}

Output

Exception in thread "main" [Link]: Unresolved


compilation problem:
The method displayName() from the type A6 is not visible
Page 111 | 180
at [Link]([Link])

Public access modifier

The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.

Example

//save as [Link]
package pack;

publicclass A7 {
publicvoid msg(){[Link]("Hello");}

//save as [Link]
package mypack;
import pack.*;
publicclass B3 {
publicstaticvoid main(String[] args) {
A7 obj=new A7();
[Link]();
}
}

Output

Hello

Summary of java access modifier

Page 112 | 180


Let's understand the access modifiers by a simple table.

Access within within outside package by outside


Modifier class package subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

3.6 Apply Inheritance


Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of parent class, and you can add new methods and
fields also.

Inheritance represents the IS-A relationship, also known as parent-child


relationship.

Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

Syntax of Java Inheritance

Page 113 | 180


1. class Subclass-name extends Superclass-name

2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives
from an existing class.

In the terminology of Java, a class that is inherited is called a super class. The
new class is called a subclass.

As displayed in the above figure, Programmer is the subclass and Employee is


the superclass. Relationship between two classes is Programmer IS-A
Employee. It means that Programmer is a type of Employee.

class Employee{
floatsalary=40000;
}
class Programmer extends Employee{
Page 114 | 180
intbonus=10000;
publicstaticvoid main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}

Output

Programmer salary is:40000.0


Bonus of Programmer is:10000

In the above example, Programmer object can access the field of own class as
well as of Employee class i.e. code reusability.

Types of inheritance

When a class extends multiple classes i.e. known as multiple inheritance. For
Example:

Page 115 | 180


Note: multiple inheritance is not supported in java

Single inheritance example


File name: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
classDogextends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
publicstaticvoid main(String args[]){
Dogd=newDog();
[Link]();
[Link]();
}
}
Output
barking...
eating...

Page 116 | 180


Multilevel inheritance example
File name: [Link]
classAnimal{
void eat(){[Link]("eating...");}
}
classDogextends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
publicstaticvoid main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}

Output
weeping...
barking...
eating...

super keyword

The super keyword in java is a reference variable which is used to refer


immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.

Usage of java super keyword

1. super can be used to refer immediate parent class instance variable.


Page 117 | 180
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1. super is used to refer immediate parent class instance variable

We can use super keyword to access the data member or field of parent class. It
is used if parent class and child class have same fields.

cl

Output

black
white

In the above example, Animal and Dog both classes have a common property
color. If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.

2. super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.

1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){[Link]("eating bread...");}
6. void bark(){[Link]("barking...");}

Page 118 | 180


7. void work(){
8. [Link]();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. [Link]();
16. }}

Output

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call
eat() method from Dog class, it will call the eat() method of Dog class by default
because priority is given to local.

To call the parent class method, we need to use super keyword.

3. super is used to invoke parent class constructor

The super keyword can also be used to invoke the parent class constructor. Let's
see a simple example:

1. class Animal{
2. Animal(){[Link]("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. [Link]("dog is created");
Page 119 | 180
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }

14. }

Output

animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler if


there is no super() or this()

As we know well that default constructor is provided by compiler automatically


if there is no constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the


compiler implicitly.

Page 120 | 180


1. class Animal{
2. Animal(){[Link]("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. [Link]("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
Output
animal is created
dog is created

Super example: real use

Here, Emp class inherits Person class so all the properties of Person will be
inherited to Emp by default. To initialize all the property, we are using parent
class constructor from child class. In such way, we are reusing the parent class
constructor.

1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. [Link]=id;
6. [Link]=name;

Page 121 | 180


8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. [Link]=salary;
14. }
15. void display(){[Link](id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. [Link]();
21. }}
Output
1 ankit 45000

3.7 Apply Polymorphism


Polymorphism in java

Polymorphism in java is a concept by which we can perform a single action by


different ways. Polymorphism is derived from 2 greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.

There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.

If you overload static method in java, it is the example of compile time

Page 122 | 180


polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime polymorphism

Runtime polymorphism or Dynamic Method Dispatch is a process in which a


call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of


a superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is
known as upcasting. For example:

1. class A{}
2. class B extends A{}

1. A a=new B();//upcasting

Page 123 | 180


Example of java runtime polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class
extends Bike class and overrides its run() method. We are calling the run method
by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, subclass method is invoked
at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

1. class Bike{
2. void run(){[Link]("running");}
3. }
4. class Splender extends Bike{
5. void run(){[Link]("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. [Link]();
10. }
11. }

Output

Output:running safely with 60km.

Another example

Consider a scenario, Bank is a class that provides method to get the rate of
interest. But, rate of interest may differ according to banks. For example, SBI,

Page 124 | 180


ICICI and AXIS banks are providing 8.4%, 7.3% and 9.7% rate of interest.

1. class Bank{
2. float getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. float getRateOfInterest(){return 8.4f;}
6. }
7. class ICICI extends Bank{
8. float getRateOfInterest(){return 7.3f;}
9. }
10. class AXIS extends Bank{
11. float getRateOfInterest(){return 9.7f;}
12. }
13. class TestPolymorphism{
14. public static void main(String args[]){
15. Bank b;
16. b=new SBI();
17. [Link]("SBI Rate of Interest: "+[Link]());
18. b=new ICICI();
19. [Link]("ICICI Rate of Interest: "+[Link]());
20. b=new AXIS();

Page 125 | 180


21. [Link]("AXIS Rate of Interest: "+[Link]());
22. }
23. }

Output

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Runtime polymorphism with data member

Method is overridden not the datamembers, so runtime polymorphism can't be


achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we
are accessing the datamember by the reference variable of Parent class which
refers to the subclass object. Since we are accessing the datamember which is not
overridden, hence it will access the datamember of Parent class always.

1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. [Link]([Link]);//90
10. }
Output
90

Runtime polymorphism with multilevel inheritance

1. class Animal{

Page 126 | 180


2. void eat(){[Link]("eating");}
3. }
4. class Dog extends Animal{
5. void eat(){[Link]("eating fruits");}
6. }
7. class BabyDog extends Dog{
8. void eat(){[Link]("drinking milk");}
9. public static void main(String args[]){
10. Animal a1,a2,a3;
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. [Link]();
15. [Link]();
16. [Link]();
17. }
18. }
Output
Eating
eating fruits
drinking Milk

3.8 Apply encapsulation, package and access


protections
A java package is a group of similar types of classes, interfaces and sub-
packages.

Package in java can be categorized in two form, built-in package and user-
defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io,
Page 127 | 180
util, sql etc.

Here, we will have the detailed learning of creating and using user-defined
packages.

Advantages of java package

1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Page 128 | 180


Simple example of Java Package
The package keyword is used to create a package in java.
1. //save as [Link]

2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
Accessing a package from another package

There are three ways to access the package from outside the package.

1. import package.*;
2. import [Link];
3. fully qualified name.

1. using packagename.*;

If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example
//save as [Link]
package pack;

publicclass A7 {
publicvoid msg(){[Link]("Hello");}
Page 129 | 180
}

//save as [Link]
package mypack;
import pack.*;
publicclass B3 {
publicstaticvoid main(String[] args) {
A7 obj=new A7();
[Link]();
}
}
Output
Hello

2) Using [Link]

If you import [Link] then only declared class of this package will be
accessible.

Example of package by import [Link]

//save as [Link]
package pack;

publicclass A7 {
publicvoid msg(){[Link]("Hello");}

//save as [Link]
package mypack;
import pack.A7;
publicclass B3 {

Page 130 | 180


publicstaticvoid main(String[] args) {
A7 obj=new A7();
[Link]();
}
}
Output
Hello

3.9 Apply Abstraction


Abstract class
A class that is declared as abstract is known as abstract class. It needs to be
extended and its method implemented. It cannot be instantiated.
Example

1. abstract class A{}

Abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.

1. abstract void printStatus();//no body and abstract

Example of abstract class with abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){[Link]("running safely..");}
6. public static void main(String args[]){

Page 131 | 180


7. Bike obj = new Honda4();
8. [Link]();
9. }
10. }
Output
running safely..
Real scenario

In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes. Mostly, we don't know about the implementation
class (i.e. hidden to the end user) and object of the implementation class is
provided by the factory method.

A factory method is the method that returns the instance of the class. We will
learn about the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.

[Link]

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by
5. class Rectangle extends Shape{
6. void draw(){[Link]("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){[Link]("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided through method

Page 132 | 180


etShape() method
15. [Link]();
16. }
17. }

Output

drawing circle

Another example

[Link]

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10. class TestBank{
11. public static void main(String args[]){
12. Bank b;
13. b=new SBI();
14. [Link]("Rate of Interest is: "+[Link]()+" %");
15. b=new PNB();
16. [Link]("Rate of Interest is: "+[Link]()+" %");
17. }}

Output

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Page 133 | 180


Abstract class having data member, abstract method, methods etc

An abstract class can have data member, abstract method, method body,
constructor and even main() method.

File name: [Link]

1. //example of abstract class that have method body


2. abstract class Bike{
3. Bike(){[Link]("bike is created");}
4. abstract void run();
5. void changeGear(){[Link]("gear changed");}
6. }
7.
8. class Honda extends Bike{
void run(){[Link]("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
[Link]();
}

LEARNING UNIT 4 – PROCESS STRING AND ARRAYS


Learning Outcomes:
4.1 Apply single dimension
4.2 Apply Multiple dimension

Page 134 | 180


4.3 Correct reading creation of a string
4.4 Proper use of String Manipulation methods

Learning Outcome: 4.1 Apply single dimension

Normally, an array is a collection of similar type of elements which have a contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Page 135 | 180


Advantages

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

Types of Array in java

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example of Java Array


Page 136 | 180
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

Output:
10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.


Page 137 | 180
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

Output:

33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){
//body of the loop
}

Let us see the example of print the elements of Java array using the for-each loop.

//Java Program to print the array elements using for-each loop

Page 138 | 180


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i);
}}

Output:

33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

//Java Program to demonstrate the way of passing an array


//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];

Page 139 | 180


[Link](min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}

Output:

Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.

//Java Program to demonstrate the way of passing an anonymous array


//to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<[Link];i++)
[Link](arr[i]);
}

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}

Page 140 | 180


Output:

10
22
44
66

Returning Array from the Method

We can also return an array from the method in Java.

//Java Program to return an array from the method


class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}

public static void main(String args[]){


//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<[Link];i++)
[Link](arr[i]);
}}

Output:

10

Page 141 | 180


30
50
90
60

ArrayIndexOutOfBoundsException

The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the


array in negative, equal to the array size or greater than the array size while traversing the array.

//Java Program to demonstrate the case of


//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=[Link];i++){
[Link](arr[i]);
}
}}

Output:

Exception in thread "main" [Link]: 4


at [Link]([Link])
50
60
70
80

Page 142 | 180


Learning Outcome: 4.2 Apply Multiple dimension

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

Page 143 | 180


//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}

Output:

123
245
445

Addition of 2 Matrices in Java

Let's see a simple example that adds two matrices.

//Java Program to demonstrate the addition of two matrices in Java


class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
Page 144 | 180
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
[Link](c[i][j]+" ");
}
[Link]();//new line
}

}}

Output:

268

6 8 10

Multiplication of 2 Matrices in Java

In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the
columns of the second matrix which can be understood by the image given below.

Page 145 | 180


Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

//Java Program to multiply two matrices


public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


Page 146 | 180
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
[Link](c[i][j]+" "); //printing matrix element
}//end of j loop
[Link]();//new line
}
}}

Output:

666

12 12 12

18 18 18

Learning Outcome: 4.3 Correct reading creation of a string


java String Methods

Java String length(): The Java String length() method tells the length of the string. It returns
count of total number of characters present in the String. For example:

public class Example{

public static void main(String args[]{


Page 147 | 180
String s1="hello";

String s2="whatsup";

[Link]("string length is: "+[Link]());

[Link]("string length is: "+[Link]());

}}

Here, String length() function will return the length 5 for s1 and 7 for s2 respectively.

Java String compareTo(): The Java String compareTo() method compares the given
string with current string. It is a method of ‘Comparable’ interface which is implemented
by String class. Don’t worry, we will be learning about String interfaces later. It either
returns positive number, negative number or 0. For example:

public class CompareToExample{

public static void main(String args[]){

String s1="hello";

String s2="hello";

String s3="hemlo";

String s4="flag";

[Link]([Link](s2)); // 0 because both are equal

[Link]([Link](s3)); //-1 because "l" is only one time lower than "m"

Page 148 | 180


[Link]([Link](s4)); // 2 because "h" is 2 times greater than "f"

}}

This program shows the comparison between the various string. It is noticed that

if s1 > s2, it returns a positive number

if s1 < s2, it returns a negative number

if s1 == s2, it returns 0

Java String concat() : The Java String concat() method combines a specific string at the
end of another string and ultimately returns a combined string. It is like appending
another string. For example:

public class ConcatExample{

public static void main(String args[]){

String s1="hello";

s1=[Link]("how are you");

[Link](s1);

}}

The above code returns “hellohow are you”.

Java String IsEmpty() : This method checks whether the String contains anything or
not. If the java String is Empty, it returns true else false. For example:

Page 149 | 180


public class IsEmptyExample{

public static void main(String args[]){

String s1="";

String s2="hello";

[Link]([Link]()); // true

[Link]([Link]()); // false

}}

Java String Trim() : The java string trim() method removes the leading and trailing
spaces. It checks the unicode value of space character (‘u0020’) before and after the
string. If it exists, then removes the spaces and return the omitted string. For example:

public class StringTrimExample{

public static void main(String args[]){

String s1=" hello ";

[Link](s1+"how are you"); // without trim()

[Link]([Link]()+"how are you"); // with trim()

}}

In the above code, the first print statement will print “hello how are you” while the second
statement will print “hellohow are you” using the trim() function.

Page 150 | 180


Java String toLowerCase() : The java string toLowerCase() method converts all the
characters of the String to lower case. For example:

public class StringLowerExample{

public static void main(String args[]){

String s1="HELLO HOW Are You?”;

String s1lower=[Link]();

[Link](s1lower);}

The above code will return “hello how are you”

Java String toUpper() : The Java String toUpperCase() method converts all the
characters of the String to upper case. For example:

public class StringUpperExample{

public static void main(String args[]){

String s1="hello how are you";

String s1upper=[Link]();

[Link](s1upper);

}}

The above code will return “HELLO HOW ARE YOU”.

Page 151 | 180


LEARNING UNIT 5 – HANDLE EXCEPTIONS
Learning Outcomes: 5.1 Proper throwing of exception to avoid risks at runtime.
5.2 Correct use of try statement to separate the logic that might throw an
exception from the logic to handle that exception.
5.3 Correct identification of common exceptions correct creation of custom
Exceptions

Learning Outcomes: 5.1 Proper throwing of exception to avoid risks at runtime.


Exception Handling in Java is one of the effective means to handle the runtime errors so that
the regular flow of the application can be preserved. Java Exception Handling is a mechanism
to handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception such as the name and description of the exception and the state of the
program when the exception occurred.
An exception can occur for many reasons. Some of them are:
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file
What is an Error?
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle
errors.

Error vs Exception

Page 152 | 180


Error: An Error indicates a serious problem that a reasonable application should not try
to catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.

Exception Hierarchy

All exception and errors types are subclasses of class Throwable, which is the base class of
the hierarchy. One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. NullPointerException is an example of such an
exception. Another branch, Error is used by the Java run-time system (JVM) to indicate
errors having to do with the run-time environment itself(JRE). StackOverflowError is an
example of such an error.

Page 153 | 180


Learning Outcomes: 5.2 Correct use of try statement to separate the logic that might throw
an exception from the logic to handle that exception.
Java exception handling is managed via different keywords: try, catch, throw, hrows and finally.

If an exception occurs within the try block, it is thrown. Your code can catch this exception using catch
and handle it.

Java try and catch:The try statement allows you to define a block of code to be tested for errors while it
is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.

Syntax

try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

When executing Java code, different errors can occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical term
for this is: Java will throw an exception (throw an error).

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being
[Link] catch statement allows you to define a block of code to be executed, if an error
occurs in the try [Link] try and catch keywords come in pairs:

try {

// Block of code to try

catch(Exception e) {

Page 154 | 180


// Block of code to handle errors

Learning Outcomes: 5.3 Correct identification of common exceptions correct creation of


custom Exceptions

Types of Exceptions

Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.

Exceptions can be categorized into 2 Ways:


1. Built-in Exceptions
 Checked Exception
 UncheckedException

Page 155 | 180


2. User-Defined Exceptions
1. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java
libraries. These exceptions are suitable to explain certain error situations.
 Checked Exceptions: Checked exceptions are called compile-time exceptions
because these exceptions are checked at compile-time by the compiler.
 Unchecked Exceptions: The unchecked exceptions are just opposite to the
checked exceptions. The compiler will not check these exceptions at compile time.
In simple words, if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a compilation error.

LEARNING UNIT 6 – DEVELOP GUI USING AWT


Learning Outcomes:
6.1 Work with windows according to AWT components
6.2 Work with graphics
6.3 Work with text
6.4 Apply AWT controls
6.5 Manage Layouts
6.6 Apply AWT Menus

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavy weight i.e. its components are using the resources of underlying
operating system (OS).

The [Link] package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.

Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating
API components like TextField, ChechBox, button, etc.

Page 156 | 180


For example, an AWT GUI with components like TextField, label and button will have different look
and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the
platforms have different view for their native components and AWT directly calls the native subroutine
that creates those components.

In simple words, an AWT application will look like a windows application in Windows OS whereas it
will look like a Mac application in the MAC OS.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Page 157 | 180


Components

All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.

Container

The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.

It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.

Note: A container itself is a component (see the above diagram), therefore we can add a container inside
container.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

Window

The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window. We need to create an instance of Window class to create this container.

Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for
holding the components. It can have other components like button, text field etc. An instance of Panel
Page 158 | 180
class creates a container, in which we can add components.

Frame

The Frame is the container that contain title bar and border and can have menu bars. It can have other
components like button, text field, scrollbar etc. Frame is most widely used container while developing
an AWT application.

Useful Methods of Component Class


Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int Sets the size (width and height) of the
height) component.

public void Defines the layout manager for the component.


setLayout(LayoutManager m)
public void setVisible(boolean Changes the visibility of the component, by
status) default false.

Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in
AWT.
Page 159 | 180
AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.

[Link]

// importing Java AWT class


import [Link].*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


[Link](30,100,80,30);

// adding button into frame


add(b);
// frame size 300 width and 300 height
setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager

Page 160 | 180


setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}

The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets
the position of the awt button.

Output:

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are

Page 161 | 180


creating a TextField, Label and Button component on the Frame.

[Link]

// importing Java AWT class


import [Link].*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


[Link](20, 80, 80, 30);
[Link](20, 100, 80, 30);
[Link](100, 100, 80, 30);

// adding components into frame


Page 162 | 180
[Link](b);
[Link](l);
[Link](t);

// frame size 300 width and 300 height


[Link](400,300);

// setting the title of frame


[Link]("Employee info");

// no layout
[Link](null);

// setting visibility of frame


[Link](true);
}

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

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

Output:

Page 163 | 180


LEARNING UNIT 7 – Program GUI with Swing
Learning Outcomes:
7.1 proper Description of Swing
7.2 Prepare appropriately the working environment (Netbeans)
7.3 Proper Use Swing Controls.
7.4 Proper Use Swing menus

Learning Outcomes: 7.1 proper Description of Swing

7.1.1. Swing Basics

Swing is a set of program component s for Java programmers that provide the ability to create
graphical user interface ( GUI ) components, such as buttons and scroll bars, that are independent
of the windowing system for specific operating system . Swing components are used with
the Java Foundation Classes ( JFC ).

Page 164 | 180


Swing Java consists of Look and feel, Accessibility, Drag and Drop, etc

Swing Classes

There are number of classes in swing packages. Some of them are,


JButton :The swing push button class

JCheckBox The swing check box class

JComboBox The Swing combo box

JLabel The swing version of label

JRadioButton The swing version of a radio button

JScrollPane Encapsulates a scrollable window

JTabbedPane Encapsulates a tabbed window

JTable encapsulates a table-based control

JTextField The wing version of a text field

How to run Swing programs


1. Compose and compile the swing program with the extension .java
2. Execute the swing program as like the normal java program execution

Page 165 | 180


Learning Outcome: 7.2 Prepare appropriately the working

[Link] basic

Bean Basics a Java Bean is a software component that has been designed to be reusable in a
variety of different environments. A bean obtains all the benefits of Java’s “write-once, run-
anywhere” paradigm.
NetBeans Netbean is a free, open source platform for building rich client applications that will
run on any operating system that supports a standard JVM. It provides a rich framework of
windows, menus, tool bars, actions, etc. It is used for building a wide variety of applications.
Bean Builder The beans binding library simplifies and standardizes the coding part of java. one
can merely write a few lines of code to establish which properties of which components need to
be kept in sync, and the beans binding library handles the rest. In the NetBeans IDE, beans
binding features are integrated in the GUI Builder, so it is possible to quickly get the behavior of
an application coded soon after the visual design is established. 3.2 Creating a Project using
NetBean In the NetBeans IDE, we always work in a project where ywe store sources and files.
To create a new project, perform the following steps:
1. Select New Project from the File menu. One can also click the New Project button in the IDE
toolbar.
2. In the Categories pane, select the General node. In the Projects pane, choose the Java
Application type. Click the Next button.
3. Enter MyBean in the Project Name field and specify the project location. (Do not create a
Main class here, if we want to create a new Java class later)
4. Click the Finish button.
This figure represents the expanded MyBean node in the Projects list.

Page 166 | 180


Creating a New Form After creating a new project, the next step is to create a form within which
the JavaBeans components and other required GUI components, will be placed. To create a new
form, perform the following sequence of actions:
1. In the Projects list, expand the MyBean node, right-click on the <default package> node and
choose New|JFrame Form from the pop-up menu.
2. Enter MyForm as the Class Name.
3. Click the Finish button.
The IDE creates the MyForm form and the MyForm class within the MyBean application and
opens the MyForm form in the GUI Builder. This figure represents the Projects list, where the
MyForm class is located.

Page 167 | 180


The GUI Builder Interface
When the JFrame form is added to the application, the IDE opens the newly-created form in an
Editor tab with a toolbar containing the following buttons:
 Selection Mode enables us to select one or more objects in the Design Area.
 Connection Mode enables us to set a connection between objects by
specifying an event.
 Preview Design enables us to preview the form layout.
 Align commands enable us to align selected objects.
 Change Resizability enables us to set up vertical and horizontal resizing.
When the MyForm form opens in the GUI Builder's Design view, three additional windows
appear, enabling us to navigate, organize, and edit GUI forms.

 These windows include the following:


 Design Area. The primary window for creating and editing Java GUI forms. Source and
Design toggle buttons enable us to switch between view a class's source code and a

Page 168 | 180


graphical view of the GUI components. Click on an object to select it in the Design Area.
For a multiple selection, hold down the Ctrl key while clicking on objects.
 Inspector. Representation of a tree hierarchy of all the components in the application. The
Inspector highlights the component in the tree that is currently being edited.
 Palette. A customizable list of available components containing groups for Swing, AWT,
Borders, and Beans components. This window enables us to create, remove, and
rearrange the categories displayed in the palette using the customizer.
 Properties Window. A display of the properties of the component currently selected in the
GUI Builder, Inspector window, Projects window, or Files window.
When you click the Source button, the IDE displays the application's Java source code in the
editor. Sections of code that are automatically generated by the GUI Builder are indicated by
blue areas. These blue areas are protected from editing in the Source view. We can only edit
code appearing in the white areas of the editor when in Source view. When we make the changes
in the Design View, the IDE updates the file's sources.
Creating a Bean

To create the own bean object and add it to the palette for the bean group, execute the following
procedure:
 Select the <default package> node in the MyBean project.
 Choose New|Java Class from the pop-up menu.
 Specify the name for the new class, for example, MyBean, then press the Finish
button.
 Expand the [Link] and MyBean node and select the Bean Patterns node.
 Right-click on the Bean Patterns node and choose Add|Property from the pop-up
menu.
 Right-click the MyBean node in the MyBean project tree and choose Tools |Add
to Palette from the pop-up menu.
 Select the Beans group in the Palette tree to add the bean.
Page 169 | 180
Adding Components to the Form
One can use the Free Design of the GUI Builder and add the MyBean component and other
standard Swing components to the form (MyForm in this example).
 Select the MyForm node in the project tree.
 Drag the JLabel Swing component from the Palette window to the Design Area.
Double-click the component and change the text property to "Enter the name:".
 Drag the JTextField component from the Palette window to the Design Area.
Double-click the component and empty the text field.
 Drag the JButton component from the Palette window to the Design Area.
Double-click the component and enter "OK" as the text property.
 Add another button and enter "Cancel" as its text property.
 Align components by using the appropriate align commands.
 Before we drag the MyBean component from the Pallete must compile the
project because the MyBean component is non-visual and cannot be operated as a
visual component.
When you Drag and Drop the MyBean component it will not appear in the Design Area. See the
figure below.

Page 170 | 180


Learning Outcome: 7.3 Proper Use Swing Controls.
7.2.1. Icons and Labels

In swing icons are encapsulated by the ImageIcon class, which paints an icon from and image.
Swing labels are instances of the JLabel class. It can display text and / or an icon.

Text Fields: TextFiled allows you to edit one line of text. It can be specified with the number of
columns in the text field.

Buttons: The JButton class provides the functionality of a push button. JButton allows an icon a
string, or both to be associated with the push button.

Check Boxes: The JCheckBox class, which provides the functionality of check box. When a
check box is selected or deselected, an item event is generated.
Page 171 | 180
Radio Buttons: Radio buttons are supported by JRadioButton class. Radio buttons must be
configured into a group.

Combo Boxes Swing provides a combo box (a combination of a text field and a drop down list)
through the JComboBox class. A combo box normally displays one entry. It can also display a
drop down list that allows a user to select a different entry.

LEARNING UNIT 8 – JDBC


Learning Outcomes:
8.1 Proper connection to Mysql Database
8.2 Proper application of JDBC CRUD
8.3 Proper application of PreparedStatement interface

Learning Outcomes: 8.1 Proper connection to Mysql Database


JDBC is a Java database connectivity technology (Java Standard Edition platform) from Oracle
Corporation. This technology is an API for the Java programming language that defines how a
client may access a database. It provides methods for querying and updating data in a database.
JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to
any ODBC-accessible data source in the JVM host environment.

Java Database Connectivity is used to connect the database applications with Java
programs. JDBC is designed to be platform-independent. JDBC Application Programming
Interface defines how a program written in Java can communicate and interact with the
database.

JDBC (Java Database Connectivity) allows you to create java programs that access and
manipulate relational databases.

Page 172 | 180


JDBC API: consists of classes and interfaces for establishing connections with database, sending
SQL statements to databases, processing results of SQL statements and obtaining database
[Link] JDBC driver - interface to facilitate communication between JDBC and proprietary
databases (Oracle JDBC driver, MySQL JDBC driver, ...)

JDBC-ODBC bridge driver - allows a java program to access database through ODBC driver.

If you use driver other than JDBC-ODBC bridge driver, you should set classpath before running
the program.

8.1.1. Accessing database with JDBC (Java database connectivity)

Steps for a java program to access the database

1. Loading the driver

2. Establishing connection

3. Creating statement

4. Executing statements

5. Processing the result set

All the interfaces and classes you will use in this lesson belong to [Link] package, that is,
Connection, Statement, ResultSet.

Loading the driver

Database Driver class

Access [Link]

Page 173 | 180


MySQL [Link]

E.g. Loading driver for connecting to MySQL database

[Link] ("[Link]");

Driver Manager: JDBC provides a driver manager to load the driver using the [Link]()
method.

Connection: A connection object represents a connection with the database.

Statement: A statement object is used to send SQL statements to a database.

Prepared Statement interface extending Statement is used to execute precompiled SQL


statement with or without parameters for efficient use when repeatedly executed.

Eg. – Inserting values into course table.

PreparedStatement ps = [Link]("INSERT INTO course (subjectId, courseName,


courseNumber, title, numOfCredits) VALUES (?, ?, ?, ?, ?)");

[Link](1,"CSCI");

[Link] (2, 1301);

[Link] (3, "Introduction to Java I");

[Link] (4, 4);

[Link]();

You can create, insert, update and delete statements

ResultSet: A ResultSet is a object that contains the result of execution of a SQL query.

Page 174 | 180


Accessing and manipulating MySQL database with JDBC

To use MySQL with JDBC, you need to install MySQL Connector/[Link] Connector/J is a
JDBC driver that allows program to use JDBC to interact with MySQL

Learning Outcome: 8.2 Proper application of JDBC CRUD


The CRUD operations are equivalent to the INSERT, SELECT, UPDATE and DELETE
statements in SQL language. Although the target database system is MySQL, but the same
technique can be applied for other database systems as well because the query syntax used is
standard SQL which is supported by all relational database systems.
We will learn how to do insert, query, update and delete database records by writing code to
manage records of a table Users in a MySQL database called SampleDB.

8.2.1. Creating a sample MySQL database

Let’s create a MySQL database called SampleDB with one table Users with the following
structure:
create database SampleDB;

use SampleDB;

CREATE TABLE `users` (


`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`fullname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`user_id`)
);

Page 175 | 180


8.2.2. Connecting to the database

Supposing the MySQL database server is listening on the default port 3306 at localhost. The
following code snippet connects to the database name SampleDB by the user root and
password secret:

String dbURL = "jdbc:mysql://localhost:3306/sampledb";


String username = "root";
String password = "secret";

try {

Connection conn = [Link](dbURL, username, password);

if (conn != null) {
[Link]("Connected");
}
} catch (SQLException ex) {
[Link]();
}

Once the connection was established, we have a Connection object which can be used to create
statements in order to execute SQL queries. In the above code, we have to close the connection
explicitly after finish working with the database:
[Link]();
However, since Java 7, we can take advantage of the try-with-resources statement which will
close the connection automatically, as shown in the following code snippet:
try (Connection conn = [Link](dbURL, username, password)) {

Page 176 | 180


// code to execute SQL queries goes here...

} catch (SQLException ex) {


[Link]();
}

JDBC Execute INSERT Statement Example

Let’s write code to insert a new record into the table Users with following details:

o username: bill
o password: secretpass

o fullname: Bill Gates

o email: [Link]@[Link]

Here’s the code snippet:


String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";

PreparedStatement statement = [Link](sql);


[Link](1, "bill");
[Link](2, "secretpass");
[Link](3, "Bill Gates");
[Link](4, "[Link]@[Link]");

int rowsInserted = [Link]();


if (rowsInserted > 0) {
[Link]("A new user was inserted successfully!");
}

Page 177 | 180


JDBC Execute SELECT Statement Example

The following code snippet queries all records from the Users table and print out details for each
record
String sql = "SELECT * FROM Users";

Statement statement = [Link]();


ResultSet result = [Link](sql);

int count = 0;

while ([Link]()){
String name = [Link](2);
String pass = [Link](3);
String fullname = [Link]("fullname");
String email = [Link]("email");

String output = "User #%d: %s - %s - %s - %s";


[Link]([Link](output, ++count, name, pass, fullname, email));
}

JDBC Executing UPDATE Statement Example

The following code snippet will update the record of “Bill Gates” as we inserted previously:
String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";

PreparedStatement statement = [Link](sql);


[Link](1, "123456789");
[Link](2, "William Henry Bill Gates");
[Link](3, "[Link]@[Link]");

Page 178 | 180


[Link](4, "bill");

int rowsUpdated = [Link]();


if (rowsUpdated > 0) {
[Link]("An existing user was updated successfully!");
}

JDBC Execute DELETE Statement Example

The following code snippet will delete a record whose username field contains “bill”:
String sql = "DELETE FROM Users WHERE username=?";

PreparedStatement statement = [Link](sql);


[Link](1, "bill");

int rowsDeleted = [Link]();


if (rowsDeleted > 0) {
[Link]("A user was deleted successfully!");
}

Learning Outcome :8.3 Roper application of Prepared Statement interface

IV. REFERENCES (the proposed reference style is APA).

Page 179 | 180


1. P. Naughton and [Link] - Java2 (The Complete Reference) – ninth Edition.

2. Cay S Horstmann & Gray Gornell - Core Java - Vol I Fundamentals - Addison Wesley
Pvt. Ltd. Indian Branch.

3. [Link]
examples#CreateDatabase

4. [Link]

5. [Link]
[Link]

Page 180 | 180

You might also like