Object-Oriented Programming in Java
Object-Oriented Programming in Java
OPTION/SUB-SECTOR: IT
CREDITS: 12
Level/ Year: 2
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.
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
Page 4 | 180
Java Unary Operator Example: ++ and --..........................................................................................23
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
Disadvantages................................................................................................................................122
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
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
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:
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.
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!");
}}
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.
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.
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.
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
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
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.
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.
Page 20 | 180
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
Page 21 | 180
long 0L 8 byte
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.
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.
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.
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.
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.
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.
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.
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.
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.
additive +-
equality == !=
bitwise exclusive OR ^
Page 25 | 180
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
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
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 are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
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
class OperatorExample{
public static void main(String args[]){
[Link](10*10/5+3-1*4/2);
}}
Output:
21
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.
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
The Java right shift operator >> is used to move left operands value to right by the number of
bits specified by the right operand.
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
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
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 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.
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 is one of the most common operator. It is used to assign the value on
its right to the operand on its left.
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
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
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
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
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:
Output:
Page 37 | 180
Age is greater than 18
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:
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
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:
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
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:
Example 2:
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:
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
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:
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
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
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:
Output:
20
30
Not in 10, 20 or 30
Java allows us to use strings in switch expression since Java SE 7. The case statement should be
string literal.
Example:
Output:
We can use switch statement inside other switch statement in Java. It is known as nested switch
statement.
Example:
Output:
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:
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.
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
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:
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:
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
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:
Output:
1
Page 62 | 180
2
3
4
5
6
7
8
9
10
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
}
Example:
Output:
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:
Output:
Page 65 | 180
2
3
4
5
6
7
8
9
10
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:
Output:
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:
Page 68 | 180
}
}
}
Output:
1
2
3
4
It breaks inner loop only if you use break statement inside the inner loop.
Example:
Page 69 | 180
}
}
Output:
11
12
13
21
31
32
33
Example:
Page 70 | 180
}
}
}
Output:
1
2
3
4
Example:
Output:
1
2
3
4
To understand the example of break with switch statement, please visit here: Java Switch
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:
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.
It continues inner loop only if you use the continue statement inside the inner loop.
Example:
Output:
11
Page 74 | 180
12
13
21
23
31
32
33
Example:
Output:
Page 75 | 180
1
2
3
4
6
7
8
9
10
Java Continue Statement in do-while loop
Example:
Page 76 | 180
Output:
1
2
3
4
6
7
8
9
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
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
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.
Page 80 | 180
1) Java Single Line Comment
Syntax:
Example:
Output:
10
Syntax:
Example:
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
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.
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
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
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.
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
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
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
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:
Page 92 | 180
It reaches the method ending closing brace.
[Link]("This is [Link]!");
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
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
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
Overloading method
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.
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
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
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.
<class_name>(){}
publicclass Bike1 {
Bike1(){[Link]("Bike is created");}
publicstaticvoid main(String[] args) {
Bike1 b=new Bike1();
}
}
Output
Bike is created
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.
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.
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 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.
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
If you apply static keyword with any method, it is known as static method.
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
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.
Example
publicclass A {
inta=40;//non static
publicstaticvoid main(String[] args) {
[Link](a);
}
}
Output
Static block
Example
publicclass A2 {
static{[Link]("static block is invoked");}
publicstaticvoid main(String[] args) {
[Link]("Hello main");
}
Output
There are two types of modifiers in java: access modifiers and non-access
modifiers.
1. private
2. default
3. protected
4. public
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{
Error
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 {
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.
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
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
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
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.
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.
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
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:
Output
weeping...
barking...
eating...
super keyword
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.
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...");}
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.
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
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;
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.
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
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
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,
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();
Output
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
1. class Animal{
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.
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
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.
//save as [Link]
package pack;
publicclass A7 {
publicvoid msg(){[Link]("Hello");}
//save as [Link]
package mypack;
import pack.A7;
publicclass B3 {
Abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
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]
Output
drawing circle
Another example
[Link]
Output
An abstract class can have data member, abstract method, method body,
constructor and even main() method.
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++.
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.
arrayRefVar=new datatype[size];
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
Output:
33
3
4
5
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.
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.
Output:
33
3
4
5
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.
Output:
Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.
10
22
44
66
Output:
10
ArrayIndexOutOfBoundsException
Output:
In such case, data is stored in row and column based index (also known as matrix form).
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;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
Output:
123
245
445
}}
Output:
268
6 8 10
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.
Output:
666
12 12 12
18 18 18
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:
String s2="whatsup";
}}
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:
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
[Link]([Link](s3)); //-1 because "l" is only one time lower than "m"
}}
This program shows the comparison between the various string. It is noticed that
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:
String s1="hello";
[Link](s1);
}}
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:
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:
}}
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.
String s1lower=[Link]();
[Link](s1lower);}
Java String toUpper() : The Java String toUpperCase() method converts all the
characters of the String to upper case. For example:
String s1upper=[Link]();
[Link](s1upper);
}}
Error vs Exception
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.
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).
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 {
catch(Exception e) {
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.
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.
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating
API components like TextField, ChechBox, button, etc.
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.
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:
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.
public void setSize(int width,int Sets the size (width and height) of the
height) component.
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]
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
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:
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
[Link]
// 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();
// no layout
[Link](null);
// main method
public static void main(String args[]) {
Output:
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 ).
Swing Classes
[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.
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.
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.
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.
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.
2. Establishing connection
3. Creating statement
4. Executing statements
All the interfaces and classes you will use in this lesson belong to [Link] package, that is,
Connection, Statement, ResultSet.
Access [Link]
[Link] ("[Link]");
Driver Manager: JDBC provides a driver manager to load the driver using the [Link]()
method.
[Link](1,"CSCI");
[Link]();
ResultSet: A ResultSet is a object that contains the result of execution of a SQL query.
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
Let’s create a MySQL database called SampleDB with one table Users with the following
structure:
create database SampleDB;
use SampleDB;
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:
try {
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)) {
Let’s write code to insert a new record into the table Users with following details:
o username: bill
o password: secretpass
o email: [Link]@[Link]
The following code snippet queries all records from the Users table and print out details for each
record
String sql = "SELECT * FROM Users";
int count = 0;
while ([Link]()){
String name = [Link](2);
String pass = [Link](3);
String fullname = [Link]("fullname");
String email = [Link]("email");
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=?";
The following code snippet will delete a record whose username field contains “bill”:
String sql = "DELETE FROM Users WHERE username=?";
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]