CoreJava8 Ed PDF
CoreJava8 Ed PDF
Module Overview
In this module, students will be able to familiarize with Java and Core Java. Apart from above, they will be able to
understand Java Architecture and Advantages of the same.
Module Objective
At the end of this module, students should be able to demonstrate appropriate knowledge, and show an
understanding of the following:
Java Introduction
• Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun
Microsystems, Inc. in 1991.
• It was first released by Sun Microsystem in 1995 and later acquired by Oracle Corporation.
• Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
• Java follows the principle of WORA (Write Once, Run Anywhere) and is platform-independent.
JAVA Architecture
• As one of the main advantages of Java is that it is platform-independent.
1. JVM
2. JRE
3. JDK
• In Java, JVM (Java Virtual Machine) is a component that provides an environment for running Java Programs.
• It is very important as a developer that we should know the Architecture of the JVM, as it enables us to write
code more efficiently.
• Every Java developer knows that bytecode will be executed by JRE (Java Runtime Environment).
• But many don't know the fact that JRE is the implementation of Java Virtual Machine (JVM), which analyzes
the bytecode, interprets the code, and executes it.
• JVM stands for Java Virtual Machine, which is used to interpret an entire program line by line.
• Each operating system has different JVM, however the output they produce after execution of bytecode is
same across all operating systems.
- Load code
- Verify code
- Execute code
• It is a collection of tools that together allow the development of applications and provide a runtime
environment.
• It includes Development Tools to provide an environment to develop your Java programs and JRE to execute
your java code.
• In order to create, compile and run Java program you would need JDK installed on your computer.
- Java Micro Edition : It is useful for developing small devices like mobile phones.
- Java Standard Edition : It is useful for GUI, database access, networking, and security.
- Java Enterprise Edition : It is an enterprise platform which is mainly used to develop web and
enterprise applications.
Applications of Java
• Below are a few applications that can be created using Java programming:
Standalone Application:-
Web Application:-
- An application that runs on the server side and creates a dynamic page is called a web application.
- Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
-
Enterprise Application:-
- An application that is distributed in nature, such as banking applications, etc. is called enterprise
application.
Mobile Application:-
• An open-source framework associated with big data called Hadoop is written in Java.
• By mingling the science of Robotics with Java programming and Artificial Intelligence, self-driving cars are
being developed.
• There are even more IDEs available. But for now, you can consider one of the following :-
Notepad − On a Windows machine, you can use any simple text editor like Notepad, or TextPad.
• Trainer will make group of participants and ask them to explain Java architecture and advantages with the
help of Mind-Mapping on paper/word/ppt/paint/etc.
• Deciding which editor or IDE will best suit you depends on several things, including the nature of the projects,
the process used by the development team, and your level and skills as a programmer.
• Eclipse is the most popular Java IDE, it is free and open-source and is written mostly in Java, although its
plugin architecture allows Eclipse to be extended in other languages.
http://www.eclipse.org/downloads/eclipse-packages
• Click on the link 32-bit or 64-bit (depending on the bit version of your operating system) to start downloading
the package.
• In order to write and run a Java program, you need to install a software program called JDK.
• Trainer to ask Participants to search for videos which shows Installation for JDK and Eclipse
• Once that is done, participants will install JDK and Eclipse in their respective PC’s under Trainer’s guidance.
• 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, etc.
• To create a package
• Right click on the project, and select New > Package from the list menu.
• Enter the name of your package (type any name of your choice).
• Click Finish. You should see the newly created package appears.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
First Java Program
• Lets begin with first java program
• To create a new Java class under a specified package, right-click on the package (net.codejava) and select New
> Class from the list menu.
• The New Java Class dialog appears, type the name of class as HelloWorld and choose the option to generate
the main() method and click Finish.
• static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of
the static method is that there is no need to create an object to invoke the static method.
• Here, System is a class, out is the object of PrintStream class, println() is the method of PrintStream class.
Lab Activity:
• Trainer to explain the participants’ how to create an account in GitHub, create repositories and push the code.
• After creating an account on GitHub, trainer to ask participants to create repositories and push the code and
share it with the trainer.
Learners will push their respective projects in their own repositories as and when informed by the trainer.
Once pushed, learners will share the respective GitHub link with the trainer.
3. Then the student needs to clear one small puzzle activity to avoid “I am robot”.
Next step-3 What do you plan to use GitHub for? So, we will give "Host a project (repository)".
Step - 4 I am interested in: So give your interest area like framework, network or etc...
4. Please verify your email address. You will have received one GitHub confirmation mail in your registered mail.
6. Then give your Repository name (HTML, CSS JavaScript, Bootstrap, Python, Ruby on Rails).
13. Inside your repository, you can create your own program or else you can add existing file from your PC.
15. If you share that URL to anyone that person also can add program files and download your files directly from
their systems.
• The java comments are statements that are not executed by the compiler and interpreter.
ADVANTAGES OF JAVA
The advantages of Java are as follows:
2. Java is object-oriented.
3. Java is platform-independent.
6. Java is Free
Data Types
• Data types in Java define the type of information that a variable can hold.
• In simple words, when we declare a variable in java then it is necessary to tell the data type of that variable
means which kind of value that variable is going to store.
• The data types defines the type of values that a variable can take, for example, if a variable has a float data
type, it can only take float values.
• Each data type reserve different size of space in memory and they can store only that type of information
which is their data type.
• As a programmer we should make minimum memory usage, because of this reason many type of data types
are created.
1. Byte
2. Short
3. Int
4. Long
5. Char
6. Float
7. Double
8. Boolean
• The data types byte, short, int, and long are integer primitive data types.
• Java does not support unsigned integers so all these integers are signed, positive and negative values.
• In the table listed below will help to know about the data types like its default value and default size in the
Java.
• The data type byte, short, int and long are integer primitive data types can be used to store an integer
number.
• There are only difference of size in these four data types, let’s see in detail about each.
• Suppose we want to store an integer number 27, then it is best to use byte because it will reserve only 1 byte
space in memory, since a byte is four times smaller than an integer.
• If we use int data type then it will reserve 4 byte space in memory, so we are wasting memory.
• For example, floating point or decimal numbers are used when expressing measurements (feet and inches),
time (hours, minutes, and seconds), etc.
• Decimal number is a number which contain decimal point (.), for example 66.7, 89.8 etc.,
• In java there are two floating data type which can be used to store a decimal value.
1. Float
2. Double
• Decimal values are useful because they allow more accuracy and precision.
• The float primitive data types are used to store decimal numbers.
• Float data type can not be used when you need precession like in currency.
• Double data type should never be used for precise values such as currency
• Double is preferred over a float in regular programming because it is sufficient for holding 15 decimal digits
size.
• The first 256 (numbered from 0 to 255) characters of Unicode are the ASCII set of characters only.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the exercise one.
Exercise 1:
package Hello.World;
//boolean example
System.out.println(IoT);
//byte example
byte range;
range = 127;
//short example
short range1;
range1 = -127;
System.out.println(range1);
//int example
System.out.println(range2);
//long example
System.out.println(range3);
//double example
System.out.println(number);
//float example
System.out.println(number1);
System.out.println(letter);
System.out.println(letter2);
System.out.println(letter3);
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• Non primitive types are created by the user and is not defined by Java (except for String).
• Non primitive data types are simply called "objects" because they are created, rather than predefined.
• Examples of non primitive data types are Strings, Arrays, Classes, Interface, etc.
• Non primitive data types are derived from primitive data types.
• Non primitive data types are called reference types because they refer to objects.
• Some widely used non primitive data types in Java are String, Arrays, Classes, Interface, etc.
• string is an immutable object which means it is constant and cannot be changed, once it has been created.
• There are some more terms associated with string data type, are as follows String Comparison, String
Concatenation, Concept of Substring, String class methods and its usage, StringBuffer class, StringBuilder class,
Creating Immutable class, toString() method, StringTokenizer class, etc.
1. String literal
2. Using new keyword
2. Multi-Dimensional Array
• It represents the set of properties or methods that are common to all objects of one type.
• An interface is declared like a class but the only difference is that it contains only final variables and method
declarations. It is fully abstract class.
Variables in JAVA
• Variable is the reserved memory location in the main memory, in simple words variable is the name of
memory locations where information is stored.
Value 96, int is a data type that determines this Variable that can hold integer values.
• Each variable has a specific data type, which is responsible to determine the memory space and the value or
data that can be store in that variable.
• It is user defined name, its totally depends on user for defining a variable name.
• These naming conventions help other developers to understand the code written by a developer
4. A variable name can contain numbers, alphabets, and two symbols “_” and “$”.
Types of Variables
• The basic syntax to declare variables in Java is shown below:
• Example :
• Explanation of Example : Here variable name is ”num” which is associated with Value 96, int is a data type
that determines this Variable that can hold integer values.
• Similarly we can declare more variable with different data type.
• There are three types of variables in java:
1. Local variables
2. Instance variables
3. Static variables.
• The sample code shown here will give the overview to understand and how to use 3 types of variables in java
while programming and their working.
• Local variables are visible only within the declared class, method, constructor, or block.
• We can use local variables with the same name in different functions body surrounded by braces, { }.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the exercise 2.
package Hello.World;
// Local variable
int age = 0;
//Local Variable
temp.StudentAge();
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• Instance variables are created when an object of the class is created and destroyed when the object is
destroyed.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the exercise.
Exercise 3:
package Hello.World;
class SubjectMarks {
int ScienceMarks;
int MathsMarks;
int GKMarks;
// Student 1
Subj1.MathsMarks = 80;
Subj1.GKMarks = 70;
// Student 2
Subj2.ScienceMarks = 85;
Subj2.MathsMarks = 50;
Subj2.GKMarks = 95;
System.out.println(Subj1.ScienceMarks);
System.out.println(Subj1.MathsMarks);
System.out.println(Subj1.GKMarks);
System.out.println(Subj2.ScienceMarks);
System.out.println(Subj2.MathsMarks);
System.out.println(Subj2.GKMarks);
• Static variables are declared in the same manner as instance variables are declared, the only difference is that
static variables are declared using the static keyword within a class outside any method constructor or block.
• Static variables are created at the start of program and destroyed at the end of the program.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 4:
package Hello.World;
class Student {
// static variable
public static double fees;
public static String name = "Aanh";
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Operator
Operator in JAVA
• In Java, operators are used for evaluation of expressions.
1. Unary Operator
2. Arithmetic Operator
3. Shift Operator
4. Relational Operator
5. Bitwise Operator
6. Logical Operator
7. Ternary Operator
8. Assignment Operator
• Example :
a += b, a-=b, a*=b, a/=b, a^=b, a%=b
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 5:
package Hello.World;
// Assignment Operator
int number1, number2;
number1 = 10;
System.out.println(number1);
number2 = number1;
System.out.println(number2);
// Arithmetic Operator
double output;
// Addition operator
output = number1 + number2;
System.out.println("number1 + number2 = " + output);
// Subtraction operator
output = number1 - number2;
System.out.println("number1 - number2 = " + output);
// Multiplication operator
output = number1 * number2;
System.out.println("number1 * number2 = " + output);
// Division operator
output = number1 / number2;
System.out.println("number1 / number2 = " + output);
// Remainder operator
output = number1 % number2;
System.out.println("number1 % number2 = " + output);
// Unary Operators
double number = 10, resultNumber;
boolean flag = false;
System.out.println(number++);
System.out.println(number);
System.out.println(++number);
System.out.println(number);
// Relational Operators
if (number1 > number2)
{
System.out.println("number1 is greater than number2.");
}
if (number1 < number2)
{
System.out.println("number2 is greater than number1.");
}
if (number1 == number2)
{
System.out.println("number1 is equal to number2.");
}
// Logical Operators
int number3 = 20;
boolean result;
// Logical OR Operator
result = (number1 > number2) || (number3 > number1);
// result will be true because number3 greater than number1
System.out.println(result);
// Bitwise Operator
int a = 50; /* 50 = 0011 0010 */
int b = 20; /* 20 = 0001 0100 */
int c = 0;
c = a | b; /* 54 = 0011 0110 */
System.out.println("a | b = " + c );
c = a ^ b; /* 38 = 0010 0110 */
System.out.println("a ^ b = " + c );
// Shift Operator
c = a >> 2; /* 12 = 0000 1100 */ // Right shift operator
System.out.println("a >> 2 = " + c );
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Arrays in JAVA
• An array is a collection of similar types of elements.
• An array is a container that holds data of one single type. For example, you can create an array that can hold
100 values of int type.
• To make it more clear, a pictorial representation of array elements with their corresponding index values is
shown below.
• The first element of the array is stored at the 0th index, second element of the array is stored at 1st index and
so on as shown in given figure.
Array Syntax
• In Java, an array is an object of a dynamically generated class.
Arrays Declaration
• It's possible to define array in one statement. You can replace the two line in above example with a single
statement.
• Example :
• Declaring Array :
• The elements are numbered as 0, 1, 2, ....., n-1. These numbers are called as indices.
• These numbers are used to locate the positions of elements within the array.
• The data type of an array must be specified by an int value and not long or short.
Arrays Types
• There are two types of array in JAVA
• You can create a single dimensional array by using the “new” keyword whose syntax is given below.
• It is an array in which each element is accessed by using only one index number. These index number
represents the position of the element in the array.
or
• A multi dimensional array is very much similar to a single dimensional array. It can have multiple rows and
multiple columns unlike single dimensional array, which can have only one full row or one full column.
• In java, a jagged array means to have a multi dimensional array with uneven size of rows in it.
or
• For both row and column i.e. [] [] the index begins from 0.
Cloning of Arrays
• Cloning creates copies that are clones of the original elements or reference elements.
• Cloning arrays are of two types shallow copy and deep copy in Java.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• In a single-dimensional array, a deep copy creates the clones of the original elements or reference elements.
• In a multi-dimensional array, a shallow copy is created, which means both arrays are pointing to the same
memory address.
• Cloning shallow copy and deep copy in Java are the ways of copying the attributes of one object into another
of the same type.
• Deep copy means a variable would have a copy of the original array in a different memory location.
• Shallow copy means both arrays are pointing to the same memory address. Whenever you modify one of
these arrays, you will be modifying both arrays.
Lab Activity:
Exercise 6:
package Hello.World;
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 7:
package Hello.World;
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• Disadvantages :
• Size Limit: We can store only the fixed size of elements in the array.
String
String in JAVA
• String is a sequence of characters enclosed within double quotes (" ") is known as String. It is an immutable
object.
• Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
1. String literal
1. String literal :
• String objects are stored in a special memory area known as the "string constant pool".
• This is the most common way of creating the string.
• String object can be created using new operator like java class.
• Example:
Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. So whenever a new
object is created. It will check whether the new object is already present in the pool or not. If it is present, then same
reference is returned to the variable else new object will be created in the String pool and the respective reference
will be returned.
Example
• How to perform string concatenation in java
• First example is by using arithmetic “+” operator and second is using “concat” method of String class.
• string concatenation by operator (+) method:
• Example1:
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
String str3 = “Core” + “JAVA”;
Lab Activity:
• Following is the web link which is used as a web terminal to try and test Java through JSHELL.
• So you can use this link to check the string method examples as shown below :
https://tryjshell.org/
• Participant will write & observe the simple hello word program, with the help of trainer
String Method
List of the some important methods available in the Java String are as follows:
• Length() :
• It returns the length of the string object.
• Example :
s.length()
Output : 9
• Example :
The Java String class getChars() method copies the content of this string into a specified char array. There are
four arguments passed in the getChars() method.
Example :
String s1 = "JAVA";
char[] dest=new char[4];
s1.getChars(0,4,dest,0)
System.out.println(Arrays.toString(dest));
Output : [J, A, V, A]
• toCharArray():
• This method returns a new character array created from the string characters.
• The java string toCharArray() method converts this string into character array. It returns a newly
created character array, its length is similar to this string and its contents are initialized with the
characters of this string.
Output : 0
• "Java".compareToIgnoreCase("JAVA")
Output : 0
isEmpty(), isBlank() :
charAt(int index) :
String s = "Java";
s.charAt(3)
Output: ‘a’
• These methods are used to check if the string has given prefix or suffix strings or not.
Example :
“Coking".startsWith(“king")
Output : false
“Coking".endsWith(“king")
Output : true
Example:
"Java".toUpperCase()
Output : “JAVA”
“jAVa".toLowerCase()
Output : “java”
• trim() : It trim all the leading and trailing whitespaces from a string.
• strip(): This method uses Character.isWhitespace()
• method to remove leading and trailing whitespaces from a string.
• The stripLeading() and stripTrailing() methods also remove leading and trailing whitespaces.
• Example: String s = “ Java “
s.trim()
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
Output : “Java“
repeat() :
• This method returns a new string whose value is the concatenation of this string given number of times.
• Example:
String s = “Java“
s.repeat(2)
Output: “JavaJava”
contentEquals():
String s1 = “Skillking“
s2.append(“Skillking")
s1.contentEquals(s2)
Output : true
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 8:
package Hello.World;
//There are many string methods available some String Methods are as follows
System.out.println("The length of the string: " + a.length());
System.out.println(a.toUpperCase());
System.out.println(a.toLowerCase());
System.out.println(a + b);
System.out.println(a.concat(b));
System.out.println("Character at position 5: " + a.charAt(5));
System.out.println(a.equals(b));
System.out.println(a.equalsIgnoreCase(b));
System.out.println(a.compareTo(b));
System.out.println(a.contains("X"));
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
String Method
• We can perform operations on string such as trimming, concatenating, converting, comparing, replacing
strings etc. with the help of these methods.
• Like this way there are many more important string method such as
getBytes(), equals(), hashCode() and equalsIgnoreCase(), indexOf() and lastIndexOf(), substring() and
subSequence() ,matches(), replace(), replaceFirst(), and replaceAll(), split(), lines(), indent(), transform(), format(),
• StringBuffer( int size): It accepts a whole number argument that explicitly sets the scale of the buffer.
• Example: StringBuffer s=new StringBuffer(30);
• StringBuffer(String str): It reserves area for sixteen characters while not reallocation and accepts a String
argument that sets the initial contents of StringBuffer object.
• Example: StringBuffer s=new StringBuffer(“IoT");
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 9:
package Hello.World;
str.reverse();
System.out.println(str);
System.out.println( str.capacity() );
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Enum
• Enum is a one of the special data types to declare the list of constants that enable for a variable, which have
similar meaning. For example, we create enum to manage the list of months, name of days, and other similar
kind of values.
• We declare enum with the help of enum keyword and since this holds the constant value, the constraint is to
write the value in capital letters.
• In a common real-life scenario, we can understand enum such as a short form of code word, which has a
meaning.
• In programming, when we want to hide the actual data from the end users, we prefer to use enums.
• For example, in our program we want the user to enter a number so that 0 represents Sunday and 7
represents Saturday. But when we are setting the enum for those numbers, we will set with the name of the
day instead of sequence 0 or 1, that will be Sunday, Monday, and so on and we further use the same in our
program for evaluation.
• This way, we also mislead the hackers to identify what value is being used in the program and they cannot
easily hack the program written using enum.
• We may also use the enum contact with values for mathematical formulas or assign a unique value for that
constant.
Output:
MONDAY
• Here, we have declared a enum Day, which holds name of the days and printed the first constant MONDAY as
follows
Example (The Enum class type example with contacts with values):
Output:
1
TUESDAY
• In the preceding example, Day(int name) is the constructor, which is assigning the constant value to a private
variable
• After this, we have created a getDayIndex method, which helps us to get the value of the constant.
• In the main method, we have written the following statements to get the constant and its values:
System.out.println(Day.MONDAY.getDayIndex()); // this line of code will print the value from constant
MONDAY that is 1.
System.out.println(Day.TUESDAY); // this line of code will simply print constant TUESDAY.
• NOTE: All enums implicitly extend java.lang.Enum because a class can only extend one parent class in Java.
• Control flows are the sections of a code that gets executed in sequence as they appear in the program, but
before execution.
• It checks for the condition and when the given condition becomes true, only then the section of code gets
executed.
• Now, we will study and practice the use of different control flows of Java programming such as if, if-then, if-
then-else, and switch.
• Using these statements, we manage executing flow of the program and make the decision at runtime
regarding what flow is going to be executed next in the program.
• We will also learn about loops; loops are statements using the ones we can repeat a block of code several
times based on the condition or expression.
• Until the expression returns true, the loop will keep repeating the execution of that same block of code, which
is written in the body of loop.
• We will see the types of loops available in Java programming and how to implement those in the program.
For example:
if(course==“JAVA”) {
system.out.println(“Course is JAVA.”);
}
For example:
if(course==“JAVA”) {
System.out.println(“Course is JAVA.”);
} else {
System.out.println(“Color is not red.”);
}
• The following flow chart shows the execution flow of an if-else statement:
• We need this when we must handle or check multiple conditions in a program on the same or different
patterns.
• Using the if statement, we can test and compare a single value and range of values
if(marks>= 60) {
system.out.println(“You passed with first grade.”);
} else if(marks >=45 || marks < 60) {
system.out.println(“You passed with second grade.”);
} else if(marks >=33 || marks < 45) {
system.out.println(“You passed with third grade.”);
} else {
system.out.println(“Sorry, you are fail.”);
}
• We use the switch keyword to create a switch statement in the code and pass a variable as an argument
• In the body of switch statement we declare cases with possible values to check and a default case to handle
the flow if there is no case matched with the given expression.
Example:
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
......
default:
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 10:
package Hello.World;
//Switch expression
switch(a){
//Case statements
case 1: System.out.println("I am @ Home");
break;
case 2: System.out.println("I am @ Office");
break;
case 3: System.out.println("I am @ school");
break;
//Default case statement
default:System.out.println("Not @ Home, Office, or school");
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• If we are using nested if, then the program will execute all if conditions to find the exact evaluation, but this is
not the case of a switch.
• Switch directly jumps to the matching case and does not evaluate or check the other cases from the case.
• So, this way, we make our system faster and navigate to the right block of code instead of checking every
condition.
Loops in Java
• loops are used to execute a set of instructions/ functions repeatedly.
1. do while
2. While
3. for loops
• Syntax :
while (condition)
loop statements...
• The while statement is used to iterate/repeat a block of code until the given condition remains true.
• The while statement returns Boolean value true or false after execution of expression.
• When it returns true, the cursor will go inside the body of the while block and executes the statements.
• When it returns it will not execute the code from the while block
Example
public class WhileLoop {
public static void main(String[] args) {
int a = 2;
while(a<=4) {
System.out.println(“Current value of a is “+a);
a++;
}}}
• While loop is continuously executed if the condition becomes true, until the condition becomes false to end
the loop
• When it returns true, the cursor will go inside the body of the while block and executes the statements.
• When it returns it will not execute the code from the while block
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 11:
package Hello.World;
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• The only difference between while and do while is that in do while, we check the condition later and in while,
we check the condition at the first point.
• The cursor moves inside the do while block and executes the statements written under the do block and later
it checks the condition. Hence, the do while block will always execute do part at least once, whether a
condition become true or false.
• And then, it executes the while to check the condition; if the condition returns true, then program will repeat
and execute the do statement again and again until it remains true; otherwise, the program will exit
• The do while loop executes a part of the programs at least once and execution depends upon the given
condition.
• Syntax :
do
loop statement.......
while (condition);
Output:
Current executing index :2
• The above program will get executed and execute the do statement and block of code written under the do
statement.
• Since the initial value of variable a was 2, and in the do block, we have initialize the value of a with 1, now the
value of a is 3.
• Hence, the condition will become and this program will no further execute the do statement.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 12:
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• Syntax :
loop statement.....
Output:
Value of i 1
Value of i 2
Value of i 3
Value of i 4
Value of i 5
• In the code shown, we have declared a for loop, which gets executed five times.
• We have declared and initialized an integer variable In the first parameter, we have initialized the variable i
with 1, which means this loop will begin from initial value 1.
• In the second parameter, we have defined the termination point which says that this loop will keep executing
until the value of i remain less than or equal to 5.
• In the last parameter, we have defined This expression is to increase the value of i after each iteration with i =
i + Each time this loop is executed, the value of i gets increased by 1.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 13:
package Hello.World;
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• Explanation: Here, we will understand the execution process of nested loops. Nested for loops are
executed from parent to child; it means each iteration will get executed first from parent to child, then
after it will move to parent iteration. Under the parent loop, there are multiple child loops, then
execution of all child loop gets completed first before moving to parent loop for next iteration.
Example
for(inti=1; i<=5; i++) {
System.out.println(“Value of i “+i);
for(int j=1; j<=i; j++) {
System.out.println(“value of j is ” +j);
}
}
• The break statement terminates the loop immediately, and the control of the program moves to the next
statement following the loop.
• Syntax :
break;
Example :
while (testExpression) {
// codes
Jump_Here:
while (testExpression) {
// codes
while(testExpression) {
// codes
break Jump_Here;
}
}
// control jumps here
}
• In the above example, when the statement break Jump_Here; is executed, the while loop labeled
as Jump_Here is terminated. And, the control of the program moves to the statement after the
second while loop.
• Syntax :
continue;
• There is another form of continue statement, labeled form, that can be used to skip the execution of
statement(s) that lies inside the outer loop.
• In given example we can see that the label identifier Jump_Here specifies the outer loop. Notice the use of the
continue inside the inner loop. Here, the continue statement is skipping the current iteration of the labeled
statement (i.e. outer loop). Then, the program control goes to the next iteration of the labeled statement.
Jump_Here:
while (testExpression) {
// codes
while (testExpression) {
// codes
if(testExpression) {
// codes
continue Jump_Here;
}
// codes
}
// codes
}
• classes are user defined data types and objects are an instance of a class.
• The methods and variables defined within a class are called members of the class.
• A class is a blueprint from which objects are created. So, an object is the instance(result) of a class.
• An object is a real world entity, for example chair, car, pen, bag, apple, etc.
Fig.a
Fig.b
• Attributes: The second one is used to show the attributes of the class.
• Operations: The third section is used to describe the operations performed by the class.
Fig a
Fig b
• The above fig.a and fig.b is divided into 3 parts the same way as the class.
• As the object is an actual implementation of a class, which is known as the instance of a class, but they are
used to build a prototype of a system from a practical perspective close to real-life scenarios.
Characteristics of Class
• A class is a group of objects which have common properties.
• A class in Java contains:
- Constructors
- Methods
- Fields
- Blocks
Advantages:-
1. Code reusability methods means we can use code many times by declaring only once.
Block : One or more line of code statements enclosed in braces is known as block.
A block begins with an open curly brace ({) and ends with a close curly brace (}).
Syntax of a block.
Characteristics of Object
• If we consider the real world applications, we can find many objects present around us like cars, dogs,
humans, chairs, books, etc.
- Behavior
- Identity
• State: It contains the attributes and value of an object. In simple words, it represents the data of an object.
• Behavior: It represents the functionality of an object.
• Identity: It is used internally by Java to identify the uniqueness id of the object.
• Explanation: Let's take some examples to understand the term state, behavior, and identity.
• We can see car as an object example to understand the term state, behavior, identity associated with object.
Object :- Car
Car is an object.
• Object name is car, so uniqueness of the object is car, known as Identity of an object.
• Car has 4 wheels, wiper, brake, gears, etc., so it represents the state of an object.
• Car has braking, accelerating, gearing, etc., so it represents the behavior of an object.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 14:
metro1.name ="Mumbai";
metro1.population = 23409876;
System.out.println("Details of metro city 1:");
metro1.display(); //display() method is being invoked for the object metro1
metro2.name ="Pune";
metro2.population = 45874294;
System.out.println("Details of metro city 2:");
metro2.display(); //display() method is being invoked for the object metro2
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Packages in java
• Package is a kind of bundle or container or library, where we put one or more Java classes, interfaces, and
other related entities/information.
• It means bundling the multiple related program files at one place. Package is the first statement of any Java
program.
• Packages can be categorized into two categories, the built in package and user defined package.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• Built-in packages: The already predefined package by the java compiler is known as built-in packages.
- java.util: It contains utility classes such as vectors, lists, hash tables, etc.
• User defined packages : These are the packages that are defined by the user. Now we will see how the
packages are created and used in java.
• How to create the packages in java is shown in the figure given below :
- Name of the package must be same as the directory under which this file is saved.
1. After the creation of packages, it can be imported using the ‘import’ keyword.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
2. By importing all the classes in a package.
• Access modifiers are used with Classes as well as Class variables and methods.
• It is allowed to use only public or default access modifiers with java classes.
1. Private
2. Protected
3. Public
• Access modifier is a keyword that we use to set the visibility or scope or define the boundary of variable,
method, and class.
• Default is the default access modifier when we do not write any modifier with class declaration.
• Example:
• For example, if a private variable declares within a method, then that can only be accessible within the
method body
• In the above program will generate compilation error since we are trying to access a private member of the
method firstName inside the main method
• Example:
package jack;
Save by foo.java public class foo{
public void msg(){System.out.println(“India");}
}
package mack;
import jack.*;
class moo{
Save by moo.java
public static void main(String args[]){
foo obj = new foo();
obj.msg();
}
}
• Public modifier makes everything public. The variable, method, and class declared with public modifier can be
accessible to any class and method.
• The foo class of jack package is public, so can be accessed from outside the package.
• Also msg method of this package is declared as public, so it can be accessed from outside.
• Example:
Class ParentClass
package foo.example.moo;
public class ParentClass {
protected String cityName = “Mumbai”;
protected String districtName = “CSMT”;
}
Class ChildClass
package foo.example.moo;
public class ChildClass extends ParentClass {
public static void main(String[] args) {
ChildClass childClass = new ChildClass();
System.out.println(childClass.cityName);
System.out.println(childClass.districtName);
}}
• It allows access to all classes within the same package and classes that are subclasses of other classes.
• Here, derived or subclass means protected will allow to inherit the properties from base class or parent class.
• In the above example, ParentClass has two protected variables cityName and districtName
• However, by using inheritance, when we inherit a class using the extends keyword, that inherited class
exposes all its variables and methods to the derived class.
• This creates a relationship between two classes, as in the real-world we have a relation with our father, and
we do have rights to access the assets belonging to our father.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 15:
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
public class AccessModifiersExample {
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Constructor
• Constructor is a special type of method with the same name as the class name.
• Constructor is used in various ways to declare the default variable and load or make available the
prerequisites of a program so that our program can execute smoothly.
• It contains a collection of statements that are executed at the time of object creation.
• The constructor is not mandatory for a programmer to write it for a class, but for the ease of program and
security purposes, we make constructors.
1. Default constructor
3. Parameterized constructor.
Default Constructor
• A constructor with no parameter is treated as the default constructor.
• Every time we create an object of a class using the new keyword, we initialize the default constructor.
• After this, the system implicitly calls the constructor with no parameter written in the program
• If we don't write constructor then java compiler will create one by default, This constructor is known as
default constructor.
• If you implement any constructor then you no longer receive a default constructor from Java compiler.
• Example:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 16:
package Hello.World;
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
No Argument Constructor
• Constructor with no arguments is known as no argument constructor.
• Syntax of no argument constructor is the same as default constructor, but the body can have any code, unlike
default constructor.
• Example:
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 17:
package Hello.World;
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Parameterized Constructor
• The constructor with parameters is called a parameterized constructor.
• A constructor that is not identical but different in number of parameters, type of parameters, and sequence of
parameters can be declared.
• We overload the constructor for different purposes and initialize the things based on the parameter or input
received.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 18:
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Super keyword
• The super() keyword should always be the first statement of the constructor.
• The super keyword is used to call the constructor from a super class.
• This super() will call the default constructor from the super class.
Output
• In this program, we have two classes - one is SuperMethod and another is SuperClass is the parent class of the
SuperMethod class.
• SuperClass has a parameterized constructor, which is expecting an argument string to be called. On the other
hand, SuperMethod has a default constructor.
• The above program will throw compile time exception since there is no default constructor in the parent class,
but has a parameterized constructor, which we need to call explicitly.
• To fix this compilation error, call the parent class parameterized constructor with Super() keyword
• In the constructor, we use the this() keyword to call or refer a constructor, which is defined within the same
class. this should be the first statement of a constructor. If you write this() as second
statement or later, then the system will generate a compilation error.
• A class can have any number of constructors and with the help of the this() keyword, a constructor can
communicate with other constructors within the class.
Example
Output
Constructor with three arguments.
Constructor with two arguments.
Constructor with one argument.
Default Constructor.
Method Overloading
• It allows the class to have more than one method having the same name, if their argument lists are different.
• In order to overload a method, the argument lists of the methods must differ in either of the following:
1. Number of argument :
It is allowed within the class given that the number of arguments are not the same.
Data type of argument : We have two methods with the name max(), one with argument of int type
and another method with the argument of int & float type.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 19:
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 20:
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
3. Swapping argument data type : It is allowed within the class given that the order of the data type variables are not
the same.
First method is having argument list as (int, float) and second is having (float, int). Both the methods have different
sequence of data type in argument list.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 21:
package Hello.World;
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
• Overriding is done so that a child class can give its own implementation to a method which is already provided
by the parent class.
• In this case the method in parent class is called overridden method and the method in child class is called
overriding method.
• A method declared in child class but it is already present in the parent class is known as method overriding.
• The method declared in the parent class is called overridden method and the method in the child class is
called the overriding method.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 22:
package Hello.World;
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Encapsulation
Encapsulation is the concept of hiding the data, variable, and method from external interaction. We create
encapsulation for hiding the members of class by declaring the members as private to restrict other classes from
directly interacting with variables. To expose and manage the member variables of an encapsulated class, we need to
create public getter and setter for those variables. Hiding data lets no other developer know which variable is storing
value and how manipulation of that is happening. However, a developer can use getter and setter methods to achieve
and use the functionality defined in the encapsulated class.
• We have a car that has many features and functionalities to use such as start, stop, play music, change gear
and many more. We are just using the trigger to perform the functionality, but we do not know
about internal processing and how these things are happening internally. All these features are encapsulated
into a single object that we call a car. In the same way, we are developing encapsulation in Java classes, by
hiding the actual data and encapsulating everything into a class.
Abstraction
• Abstraction is a process where you show only “relevant functional details” and “hide irrelevant details” of an
object from the user.
• Abstraction is a process of hiding the implementation details and only showing the functionality to the user.
1. Abstract class
2. Interface
Abstract class
• A class that is declared using “abstract” keyword is known as abstract class.
• A class derived from the abstract class must implement all those methods that are declared as abstract in the
parent class.
• A class can not be declared with both final and abstract keywords, because final keyword is used to prevent
overriding whereas abstract methods need to be overridden.
• We can not create an object of abstract classes. It can only be used as a reference.
• To use an abstract class, we need to create another class which extends this class.
• An abstract method does not have implementation and body. It defines only the signature of the method.
• The bird sounds differs from one bird to another, there is no point to implement this method in parent class.
• Now every child class must override this method to give its own implementation details, like duck class will say
“quack”, peacock class will say “scream” and so on.
• So now when we know that all the bird child classes will and should override this method, then there is no
point to implement this method in parent class.
• Therefore, making this method abstract would be the good choice as by making this method abstract we force
all the sub or child classes to implement this method.
• Now each bird must have a sound, by making this method abstract we made it compulsory to the child class to
give implementation details to this method.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
package Hello.World;
}
}
}
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Inheritance
• The process in which one class (object) acquires all the properties and behaviors (fields and methods) of
another class (parent) is known as inheritance.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• When we inherit from an existing class, we can reuse fields and methods of the parent class.
• Java Inheritance is one of the most important features of object oriented programming.
• We can declare new fields in the subclass that are not in the superclass.
• In real life, a child inherits the properties from his father just like that inheritance represents a parent child
relationship which is also known as IS-A relationship.
• The extends keyword defines that we are making a new class that is derived from an existing class.
• HAS-A simply mean the use of instance variables that are references to other objects. For example, Maruti has
Engine, or House has Bathroom.
• Sub Class/Child Class: It is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
• Super Class/Parent Class: The class whose properties and functionalities are used (inherited) by
another class is called as base class or a parent class.
• Reusability: We can use the same fields and methods already defined in the previous class.
• Extends keyword : It indicates that you are making a new class that derives from an existing class.
• In Java, ‘extends’ keyword is used to inherit a class. Here the ParentClass is the name of parent class from
which the ChildClass is acquiring the properties and ChildClass is the name of child class. The ChildClass is
inheriting the properties and methods of ParentClass.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
• Note: Java does not support Multiple and Hybrid Inheritance with classes. Multiple and Hybrid inheritance can
only be achieved only through Interfaces.
Single Inheritance
• Single Inheritance : In single inheritance, the features and methods of the parent class are inherited by a
single child class.
• Single inheritance enables a child class to inherit properties and behavior from a single parent class.
• It allows a child or derived class to inherit the properties and behavior of a base or parent class, thus enabling
code reusability as well as adding new features to the existing code.
• In the syntax below, the class A serves as a parent class for the child class B.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 24:
package Hello.World;
class ABC
{
public void print_ABC()
{
System.out.println("Cooking");
}
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
• Multilevel inheritance refers to a relationship between child and parent class where a class extends the child
class.
• In the syntax shown, class C extends class B and class B extends class A.
• Therefore class A serves as a base or parent class for the derived or child class B, which in turn serves as a base
or parent class for the child or derived class C.
• In the syntax below, class A serves as a parent class for the class B, and also class B serves as a parent class for
class C.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 25:
package Hello.World;
class ABC
{
public void print_ABC()
{
System.out.println("Cooking");
}
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Hierarchical Inheritance
• Hierarchical Inheritance : In hierarchical inheritance, more than one subclasses inherit the properties,
behavior, features and methods from a single parent class.
• The following image explains hierarchical inheritance, It refers to a child and parent class relationship where
more than one child classes extends the same parent class, like child class B & C extends the same parent
class A.
• In the syntax above, Class B and Class C are the subclasses of parent Class A.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 26:
package Hello.World;
class ABC
{
public void print_ABC()
{
System.out.println("Cooking");
}
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Multiple Inheritance
• Multiple Inheritance : In Multiple inheritance one class can have more than one superclass and inherit
properties, behavior, features and methods from all parent classes.
• Multiple Inheritance is a feature of object oriented concept, where a child class can inherit properties of more
than one parent class.
• So in the syntax given below child class C extends both parent classes A and B.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 27:
package Hello.World;
interface ABC
{
public void print_ABC();
interface XYZ
{
public void print_XYZ();
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Hybrid Inheritance
• Hybrid Inheritance : Hybrid Inheritance is a combination of both Single Inheritance and Multiple Inheritance.
• Since in Java Multiple Inheritance is not supported directly we can achieve Hybrid inheritance also through
Interfaces only.
• As we can see in the above diagram Class D is the Parent class for both Class B and Class C which is single
inheritance and again Class B and Class C act as Parent for Class A which is multiple inheritance.
• Java doesn’t support hybrid inheritance but it can be achieved through interface only.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• This process is known as hybrid inheritance
• Java doesn’t support hybrid inheritance but it can be achieved through interface only.
• As we can see in the above code the Class D has implemented both the interfaces class B and class C. In this
case we didn’t have ambiguity even though both the interfaces are having same method.
• In the syntax below, class D inheriting both class B and class C though interface otherwise it will give error at
runtime.
• Java doesn’t support hybrid inheritance but it can be achieved through interface only.
• As we can see in the above code the Class D has implemented both the interfaces class B and class C. In this
case we didn’t have ambiguity even though both the interfaces are having same method.
Lab Activity:
Exercise 28:
package Hello.World;
interface A
{
public void A();
}
interface B extends A
{
public void B();
}
interface C extends A
{
public void C();
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants
Interface
• Interface looks like a class but it is not a class.
• An interface can have methods and variables just like the class but the methods declared in interface are by
default abstract means only method syntax is defined not body.
• Defining an interface is similar to defining a class, but a class describes the attributes and behaviors of an
object, and an interface contains behaviors that a class implements.
• An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface.
• Let’s understand the concept of Polymorphism in Java with a real time example.
• Life cycle is the developmental stages that occur during an organism’s life time.
• The major stages of the human life cycle include pregnancy, infancy, the toddler years, childhood, teenager,
adulthood, middle age, and the senior years i.e. old age, Here one person present in different different
behaviors.
• so it means having many forms, therefore polymorphism can be defined as a mechanism for getting different
characteristics of the same instance.
• Polymorphism is not a programming concept but it is one of the principal of objects oriented programming
language.
• For many objects oriented programming language polymorphism principle is common but implementations
are varying from one objects oriented programming language to another object oriented programming
language.
• There are mainly two types of polymorphism in Java as shown below:
- compile-time polymorphism
- Runtime polymorphism
• When there are multiple functions with same name but different arguments then these functions are said to
be overloaded.
• In order to overload a method, the argument lists of the methods must differ in either of the following:
• Method Overloading allows to have more than one method having the same name, if the arguments of
methods are different in number, sequence and data types of parameters.
• In the following example, we have three definitions of the same method max().
• So the max method would be determined by its arguments at the compile time that’s why it is known
as Compile Time Polymorphism.
Early Binding
• It is a compile time process.
• The method definition and method call are linked during the compile time.
• The binding of static, private and final methods are done at compile time.
Runtime Polymorphism
• Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime, thats why
it is called runtime polymorphism.
• Overriding allows a child class to implement a method that is already provided by one of its parent class.
• Let us consider a scenario where bank is the parent class which provides functionality of deposit & withdrawal,
also there are two child classes overriding these functions.
Late Binding
• It is a run time process.
• The method definition and method call are linked during the run time.
• The binding of static, private and final methods are not done.
Exception Handling
• An Exception is an unwanted event that interrupts the normal flow of the program.
• Some of these errors do not show up at compile time but interrupts the normal flow of execution at run time.
• An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
• This is something that every programmer faces at any point of coding. They can occur from different kind of
scenarios like entering the wrong data by user, hardware failure, network failure, class not found, out of
memory, etc.
• The main advantage of exception handling is to maintain the normal flow of the application.
• All exception and errors types are sub classes of class Throwable.
• Suppose if an exception is not handled, it may lead to a system failure. That is why handling an exception is
very important.
• Java provides specific keywords for exception handling like throw, throws, try, catch, finally.
• According to oracle an error is also considered as the type of exception, but error is also considered as the
unchecked exception, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
• These exceptions occur at compile time and without handling them, the program cannot be executed.
Unchecked Exception
• An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime
Exceptions.
Error
• Errors in Java are normally overlooked.
1. try
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
2. catch
3. finally
4. throw
5. throws
The “try” keyword is a block where we put exception code. The “try” block cannot be used alone. A try block
must be followed by catch blocks or finally block or both.
Syntax :
try{
It must be used along with “try” block. It is used to handle the exception. Multiple catch blocks are possible in Java to
handle multiple types of exceptions. The catch block catches the exception thrown by the try block.
Syntax :
try {
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 29:
package Hello.World;
try
{
int[] numbers = {1, 2, 3};
System.out.println(numbers[50]);
}
catch (Exception e)
{
System.out.println("Some Error in code.");
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Syntax:
try
{
// statements which cause an exception
}
catch
{
// code for handling error
}
finally
{
// Statements to be executed
}
• A finally block appears at the end of the catch blocks and has the following syntax.
• The statements present in this block will always execute regardless of whether exception occurs in try block
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
package Hello.World;
try
{
int[] numbers = {1, 2, 3};
System.out.println(numbers[50]);
}
catch (Exception e)
{
System.out.println("Some Error in code.");
}
finally
{
System.out.println("The finally statement lets you execute code, after try...catch, "
+ "regardless of the result");
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Syntax :
throw exception;
• throw: The “throw” keyword is used to throw a user defined exception from a method or any block of code.
We can throw either checked or unchecked exception in java by throw keyword.
Syntax :
throw exception;
Example :
• In this example, we have created the validate method that takes number value as input in the form of
arguments. If the divisor value is zero, we are throwing the ArithmeticException.
• ArithmeticException is thrown to indicate that a method has been passed an illegal or inappropriate argument
when the divisor is zero.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 31:
package Hello.World;
Age(14);
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Syntax :
// definition of method
Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by
using the throws keyword.
• It allows the programmers to program at the interfaces, instead of the actual implementation.
• A well designed framework can improve your productivity and provide ease of maintenance.
1. A set of interfaces
2. Implementation classes
• Java Collections are similar to containers that consists of multiple items in a single unit. for e,g. collections of
books, list of names etc.
• Collections framework provides unified architecture for manipulating and representing collections.
• Collection framework contains different types of collections such as lists, sets, maps, stacks, queues, etc.
• Collection interface is the root interface from which the interfaces List, Set,Queue are extended.
• There are some other classes in collection framework which do not extend Collection Interface they
implement Map interface.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• Collections Interfaces :
- List, Queue and Set are all sub interfaces of collection interface.
• List Interface :
- The classes which implement the List interface are called as Lists.
- List interface is an ordered collection in which duplicate elements are also allowed.
- Queue is a data structure in which elements are added from one end and elements are deleted from
another end.
- It follows FIFO pattern i.e. First in First out except priority queue.
• Deque Interface:
- The Deque Interface is the short name for “Double Ended Queue”.
- The Deque interface defines the methods needed to insert, retrieve and remove the elements from both
ends.
• Set Interface:
- Methods are inherited from collection interface as it does not have it’s own methods.
• SortedSet Interface:
- Map is an object of key-value pairs where each key is associated with a value.
- A map can not have duplicate keys but can have duplicate values.
- The common implementations of Map interface are HashMap, LinkedHashMap and TreeMap.
• SortedMap Interface:
- The SortedMap interface includes all the methods of the Map interface.
- In order to use the functionalities of the SortedMap interface, we need to use the class TreeMap that
implements it.
• NavigableMap Interface :
- In order to use the functionalities of the NavigableMap interface, we need to use the TreeMap class that
implements Navigable Map.
• ArrayList Class:
- ArrayList is same like normal array but it can grow and shrink dynamically to hold any number of elements.
- In Arraylist first element will be placed at index 0 and last element at index n-1.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 32:
import java.util.ArrayList;
public class arrayList {
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add(“FIRST”);
list.add(“SECOND”);
list.add(“THIRD”);
list.add(“FOURTH”);
list.add(“FIFTH”);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println(“Size of array ” + list.size());} }
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• Vector Class:
- The Vector Class is also dynamically growable and shrinkable collection of objects like an ArrayList class.
- Vector class is preferred over ArrayList class for multi threaded application.
- All methods of Vector class are synchronized so that only one thread can execute them at any given time.
- Each node consist of 3 parts i.e. Reference To Previous Element, Value Of The Element and Reference To
Next Element.
- Elements can be inserted at both the ends and also in the middle of the LinkedList.
- The LinkedList can be used as stack. It has the methods pop() and push() which make it to function as
Stack.
• PriorityQueue Class:
- Elements in the PriorityQueue are arranged according to supplied Comparator, if not than elements will
be placed in their natural order.
- The PriorityQueue is a special type of queue because it is not a First in First out (FIFO) as in the normal
queues.
- PriorityQueue class extends AbstractQueue class which in turn implements Queue interface.
• ArrayDeque Class:
- It does not have any restrictions on capacity. It expands automatically as we add more elements.
- The ArrayDeque class extends AbstractCollection class and implements Deque interface. It also
implements Cloneable and Serializable marker interfaces.
• HashSet Class:
- The HashSet class in Java is an implementation of Set interface. HashSet is a collection of objects which
contains only unique elements.
- HashSet class extends AbstractSet class and implements Set interface. It also implements Cloneable and
Serializable marker interfaces.
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 33:
import java.util.HashSet;
import java.util.Iterator;
public class HashSetCollection
{
public static void main(String[] args)
{
HashSet cities = new HashSet();
// Below line of code will remove element from HashSet
cities.add("New Delhi");
cities.add("Mumbai");
cities.add("Chennai");
cities.add("Kolkata");
cities.remove("New Delhi");
Iterator iterator = cities.iterator();
while(iterator.hasNext()) {
String nameOfCity=(String) iterator.next();
System.out.println(nameOfCity);
}}}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• LinkedHashSet Class:
- LinkedHashSet internally uses LinkedHashMap to store it’s elements just like HashSet.
- The LinkedHashSet class extends HashSet class and implements Set interface. It also implements
Cloneable and Serializable marker interfaces.
• TreeSet Class:
- Elements in TreeSet are sorted according to supplied Comparator, if not than elements will be placed in
ascending order.
- TreeSet internally uses TreeMap to store it’s elements just like HashSet and LinkedHashSet
- The TreeSet class in java is a direct implementation of NavigableSet interface which in turn extends
SortedSet interface
Lab Activity:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 34:
import java.util.TreeSet;
public class TreeSetJavaCollection
{
public static void main(String[] args)
{
TreeSet treeSet = new TreeSet();
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
• TreeMap class:
- TreeMap provides an efficient way to store key/value pairs in sorted ascending order.
- Java TreeMap contains only unique elements keys duplication are not possible.
- Java TreeMap cannot have a null key but can have multiple null values.
File Input/Output
File
• The File class is the class that provides access to the file system to JVM.
• A relative path must be interpreted in terms of information taken from some other pathname or current path
of the application, which is typically the path where JVM is running the application and program.
• An absolute pathname is complete, including drive and directory in which no other information is required to
locate the file.
• By default, the classes in the java.io package always resolve relative pathnames against the current user
directory
Example:
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) throws IOException {
File newFile = new File("ListOfCourses.txt");
if (newFile.createNewFile()) {
System.out.println("File created.");
} else {
System.out.println("File exists.");
}}}
Output:
File created.
• These program will create the file, ListOfCourses.txt under the current project directory, because we have
given only the filename as a parameter of the File class, which will be treated as a relative path by JVM.
• The next line of code is checking the file presence of file with the same name in the system using the method
createNewFile() that returns true or false.
• Based on the return of we are printing a text message on console; so, in our case, the method returns true and
create a file.
• Hence the cursor goes in to the if section and prints the message “File created”
• Byte Byte Streams are used to perform input and output of 8-bit bytes. Classes such as FileInputStream and
FileOutputStream support byte streams.
• Character Character Streams are used to perform input and output of 16-bit Unicode characters. Classes such
as FileReader and FileWriter support character streams
• When a third-party application of human interact with system, the system will expect some input to process
further steps.
• Input Stream helps us to read the bytes coming from external sources.
• InputStream is an abstract class and super class of all the input classes
• FileReader is the class that helps to read the characters or text from file using the default buffer size.
• This only reads the stream of characters from file and makes a connection with the file.
FileInputStream
• FileInputStream is a class that helps us to obtain input byte from file and build a connection between file
stored in the storage system and application.
• The syntax of FileInputStream constructor for opening connection to a file, the parameter object or name is
the file stored in the file system:
FileInputStream(File fileObject) or
FileInputStream(String fileName)
• This is an abstract class, and its sub-classes get implemented to generate the output.
FileOutputStream
• FileOutputStream is used to create a file in the filesystem and write data into that file.
• If you try to write data into an existing file using FileOutputStream and that named file doesn’t exist in the file
system, then FileOutputStream will create a file with given name and add the data into it.
• To create a file using FileOutputStream, we need to pass an argument that will call the constructor and create
the file. The argument can be an absolute or relative path of the file, or an object of File class
Example:
import java.io.FileOutputStream;import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamExample {
public static void main(String args[]) {
try {
OutputStream oStream = new FileOutputStream("Output.txt");
oStream.write(70);
oStream.write(65);
oStream.write(78);
oStream.close();
System.out.println("Successfully created and written the file.");
} catch (IOException e) {
System.out.print("Exception");
}}}
• The preceding program will successfully create a file Output.txt in the current directory and write the Unicode
characters for numbers 70, 65, and 78 (FAN).
InputStreamReader
• The InputStreamReader, a sub-class of the Reader class
is a bridge from byte streams to character streams.
• For example:
• Writer class is an abstract class that helps to write the streams of characters. There is no direct
implementation of the Writer class, but we use its sub-classes to perform the write operation on file.
The methods and must be implemented by subclasses of the Writer class
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferReaderExample {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("ListOfCourses.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line;
while((line = reader.readLine()) != null){
System.out.println(line);
}}
catch (IOException e) {
e.printStackTrace();
}}}
Output:
Java
Python
Android
IoT
BufferedReader
• The BufferedReader class is a subclass of the Reader class that reads text or buffering characters or character
input stream and provides efficient reading of characters, lines or arrays.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• This can be used with FileReader or InputStreamReader or other readers classes to read the byte of inputs
from file or stream and return serialized and deserialized data.
Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileAndBufferedReader
{
public static void main(String[] args) throws IOException
{
FileReader fReader = new FileReader("SampleFile.txt");
BufferedReader bReader = new BufferedReader(fReader);
int records;
while((records = bReader.read()) != -1) {
System.out.print((char)records);
}
bReader.close();
fReader.close();
}}
Output:
• Here, the BufferedReader class helps to read the characters from a specified file object.
• After completion of the read operation, we close the objects and remove the references with the help of the
close() method at the end of the program.
• When we serialize an object, it means we are actually converting its state to a stream of bytes, so that the
stream of bytes can be later converted into a copy of the Java object
• We can make a Java object serializable by implementing the java.io.Serializable interface or its sub interface,
Serialization can be implemented to persist the state of any object, and travel or pass that object over the
network so that the other system or application can consume or use that stream of bytes.
• This also helps us to store the state of object into a file or database as permanent storage.
• Stream of bytes are platformindependent, which means we can serialize and deserialize on any machine or
platform, and that can be read and understood by any system.
• Mainly, we use the approach of serialization when we have some data or file, which we want to transfer to
other systems/applications or communicate with external applications.
• Serializable saves or persists only non-static member of the object; static members of an object will not get
serialized.
• If we try to serialize an object that doesn’t support serialization, then the system will throw
NotSerializableException for that.
• Deserialization is the opposite of serialization, where we transform a stream of bytes into a Java object.
• ObjectOutputStream and ObjectInputStream are the IO classes that have the writeObject and readObject
methods, which help us to write and read the state of an object for its class.
• The writeObject() method is responsible for writing the state of the object for its class and readObject()
method is responsible for reading from the stream and restoring the fields of classes.
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 35:
import java.io.*;
class Link implements Serializable {
private String commons;
private int favorites;
public Link(String commons, int favorites) {
this.commons = commons;
this.favorites = favorites;
}
public void printLink() {
System.out.println("Link : " + this.commons);
}
}
public class Serialization {
public static void serializeLink(Link inputLink, String fileName) throws IOException {
}
public static Link deserializeLink(String fileName) throws IOException, ClassNotFoundException {
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Link randomLink = new Link("My first link", 5);
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Multithreading
Threads in JAVA
• Thread is the smallest execution unit of a process and a process may have many threads that are executing at
the same time.
• Thread has its own execution path within the process and shares the memory of the process with other
threads, which are running in the same process.
• Thread doesn’t allocate any memory, but it uses the memory allocated by its process; this helps faster and
efficient communication between threads within the same process.
- Processor
- Thread
• A process always allocates separate memory in the system for the execution and has a self-contained
execution environment and executes with the same allocated memory.
• The Java virtual machine runs as a single process and executes java program within the same process, but if
needed, we can create additional processes using start() of the ProcessBuilder object.
• For example:
Process p = new ProcessBuilder(“customProcess”,“args”).start();
Thread
• A thread never allocates its own memory; it always uses the memory allocated by the processor and executes
within a process.
• Threads are very lightweight and consume fewer resources for execution.
• A simple Java program always starts with a main thread, and a thread can also create further threads to lessen
the execution of the program
• A thread can communicate with other threads running in the same process using the thread methods such as
wait(), notify(), and yield()
• Multitasking is the term use to refer when a machine or person is doing or running multiple works or tasks at
the same time.
• For example,
when we work on a computer, at the same time, there are multiple programs and applications running such as
playing music, writing on a word document, browsing Internet, and many others. So, we can say that our
computer is multitasking.
There is no multitasking where multiple tasks are being executed on the CPU. But it is all about utilizing the
CPU’s ideal time and allowing other processes or threads to execute, when one program is waiting for input or
other resources.
Introduction to Multithreading
• Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU.
• Each thread defines a separate path of execution.
• This means that a single program can perform two or more tasks simultaneously.
• For example:
Thread Lifecycle
• A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then
dies. The following diagram shows the complete life cycle of a thread.
• New : A thread begins its life cycle in the new state. It remains in this state until the program starts the start()
method.
• Runnable : After a newly born thread is started by invocating start() method on new thread, the thread
becomes runnable.
• Running : A thread is in running state if the thread scheduler has selected it.
• Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this stage the thread is
still alive.
• Terminated : A thread enter the terminated state when it complete its task.
The maximum priority that a thread can have. The logical thread value is 10. The minimum priority that a thread can
have. The logical thread value is between 1 to 4. The default priority that is assigned to a thread. The logical thread
value is between 5 to 9. To identify and get the priority of an executing thread, we may check with the help of the
getPriority() method of Thread
Thread priorities cannot guarantee that a higher priority thread will always be executed first than the lower priority
thread. The selection of the threads for execution depends upon the thread scheduler which is platform dependent.
• Every thread has a priority that determine the order in which each threads are scheduled for execution.
• In java thread priority ranges between 1 to 10
• Let create a class that implements the runnable interface as shown in syntax.
• Where,
• Once a Thread object is created, we can start it by calling start() method, which executes a call to run( )
method. Following is a simple syntax of start() method
- void start()
Example:
- Once Thread object is created, we can start it by calling start() method, which executes a call to run( ) method.
Example:
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 36:
package Hello.World;
}
}
}
}
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
Thread Synchronization
• Synchronization is a keyword in the Java programming language that facilitates the programmer to control
threads that are sharing data.
• This is the best approach in Java technology to provide a mechanism to treat the data carefully.
• Synchronized keywords are used to declare a method or create a method or block of statement thread safe,
that means only one thread can access that block of code at a time and other threads will be in a waiting state
until the first thread completes the execution.
• This is done when we want to get the updated data after evaluation or while modifying the object so that
other threads get only the updated value after the successful modification of the object.
• If we do not lock the code block, then other threads may perform the operation on the same object, which
causes ambiguity and corrupts the actual data
Trainer will ask the participants to refer to the participant’s guide and complete the given exercise.
Exercise 37:
package coreJava;
class SynchronizedEx {
synchronized void show(String p){
try {
System.out.println("*****");
System.out.print(p);
Thread.sleep(1000);
System.out.println("#####");
}
catch(InterruptedException e){
e.printStackTrace();
}}}
class MyThread implements Runnable {
Thread c;
String m;
SynchronizedEx r;
MyThread(SynchronizedEx w, String k) {
r=w;m=k;
c=new Thread(this);
}
public void run(){
r.show(m);
}}
public class test {
public static void main(String s[])throws
InterruptedException {
SynchronizedEx d=new SynchronizedEx();
MyThread t1=new MyThread(d,"Hello");
MyThread t2=new MyThread(d,"JAVA");
t1.c.start();
t2.c.start();
Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.
DeadLock
• Deadlock in Java is a part of multithreading.
• Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another
thread and second thread is waiting for an object lock that is acquired by first thread.
• Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
• Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
• Deadlock in Java is a condition when two or more threads try to access the same resources at the same time.
• Then these threads can never access the resource and eventually go into the waiting state forever.
• So, the deadlock condition arises when there are more than two threads and two or more than two resources.
• Basically, a deadlock occurs when multiple threads request for the same resource but they are received in a
different order.
• Eventually, they get stuck for an infinite period of time and cause a deadlock.
Avoid DeadLock
• Though it is not possible to completely get rid of the deadlock problem in java still we can take precautions to
avoid such deadlock conditions. These preventive measures are as follows:
Memory Management
• Heap is the memory that gets created within the RAM for random access, where classes, objects and members
created.
• Garbage collection is the backbone of JVM for dealing with memory and allocating and reclaiming the memory
from heap.
• Heap and sack are the random memory types and heap is major memory, which is being use by Java
programming.
• Heap memory is further classified into the three logical parts called generations - new, old, and permanent are
the three generations of the heap memory.
• All three generations of memory are managed and handled by minor, major, and full garbage collection that
helps to reclaim the unused memory from system by deleting the unreferenced objects from heap.
Garbage collection
• Garbage collection is the process of memory management that finds and removes or cleans the unused heap
memory allocated to the objects and keeps the memory reusable and available for new resources.
• Garbage collection executes automatically and removes the allocated memory for only those objects and
members that do not hold any references and no more in use, or in general terms, we can say reclaims the
unused heap memory
• Java virtual memory provides various garbage collectors that help the system or operating system to improve
the performance and efficiency of the memory
• There are two methods Runtime.gc() and System.gc() that generate and send the request to JVM for garbage
collection.
• We cannot force the garbage collectors to reclaim the unused memory, JVM automatically manages all these
to run the application or program and a developer need not worry about the memory management in Java.
• Garbage collection can be forcefully executed with the help of any of the following methods:
• NOTE: Calling the above methods does not guarantee that Garbage collection will start performing and
reclaiming the memory immediately. When all the heap memory is full, it will throw a
java.lang.OutOfMemoryError error.
Generations
• Java Heap memory (Hotspot heap structure) is called Generations are the logically divided spaces of heap
memory to store the resources and objects based on their life or tenure.
- Old generation
- Permanent generation
• First, we have young generation that is split into three parts, an Eden, and two survivor space S0 and S1 that
keep moving the object from one part to another by executing the Minor garbage collector.
• Second, we have old generation, also known as tenured generation, that stores the objects, which does not
get cleaned by Minor garbage collection in young generation, and if a program or application still using that
object, then that object will be moved to old generation of the heap memory. There is a threshold defined on
the age of an object in young generation. Once that threshold age met, the object automatically moves from
young to old generation. Major garbage collection runs on the old generation to clean the object and reclaim
the memory.
• The third one is permanent generation that holds the metadata of classes, objects, and members executed
and loaded in the memory of running the program or application. It also holds Java library classes and
methods. Full garbage collection runs on the permanent generation and clears the classes from memory when
those classes and methods are no more required.
2. Major GC: This runs on old generation of heap memory and responsible for cleaning the old/tenured heap
space.
3. Full GC: This is cleaning the entire heap memory, including young and tenured spaces.
• These are three garbage collectors that run on their respective generations of heap memory and keeps our
application active and running without any memory leakage issue or out of memory issue.
• The finalize() method identifies the objects that do not have any references and pushes them in the garbage
collection queue to reclaim the memory.
• The finalize() method will not send any live or active object for garbage collection.
• We can explicitly call the finalize() method on objects, when we know that we are no longer going to use this
object in the program and want to remove from memory.
• But again, it all depends on the GC, whether the memory will be reclaimed or not.
• We cannot guarantee that after calling the finalize method, memory of that object will be free and reclaimed.
• Calling the finalize() method explicitly may impact the performance of your application because of high CPU
utilization.
Heap
• The heap size in any machine depends on the maximum address space per process.
• We can control the size of heap memory for any application or program while starting the program.
• Here are the parameters that we use to set the heap size and instruct the JVM to allocate the specified heap
memory to an application
Build Tool
Any given software project may have more activities than these needed to build the finished software. Such activities
can normally be plugged into a build tool, so these activities can be automated too.
The advantage of automating the build process is that you minimize the risk of humans making errors while building
the software manually. Additionally, an automated build tool is typically faster than a human performing the same
steps manually.
Installing Maven
• To install Maven on your own system (computer), go to the http://maven.apache.org/download.cgi and
follow the instructions there:
1. Set the JAVA_HOME environment variable to point to a valid Java SDK (e.g. Java 8).
3. Set the M2_HOME environment variable to point to the directory you unzipped Maven to.
6. Open a command prompt and type 'mvn -version' (without quotes) and press enter.
• clean: deletes all artifacts and targets which are created already.
• package: package is used to convert your project into a jar or war etc.
• install: install the package into the local repository for use of another project.
• This includes the directories where the source code, test source etc. is located in, what external dependencies
(JAR files) your projects has etc.
• The POM file describes what to build, but most often not how to build it. How to build it is up to the Maven
build phases and goals. You can insert custom actions (goals) into the Maven build phase if you need to,
though.
• Each project has a POM file. The POM file is named pom.xml and should be located in the root directory of
your project. A project divided into subprojects will typically have one POM file for the parent project, and one
POM file for each subproject.
• Maven allows to comprehend the complete state of a development effort in the shortest period of time.
• All POM files require the project element and three mandatory fields: groupId, artifactId,version.
• modelVersion :- It is the sub element of project. It specifies the modelVersion. It should be set to 4.0.0.
• groupId :- It is the sub element of project. It specifies the id for the project group.
• artifactId :- It is the sub element of project. It specifies the id for the artifact (project). An artifact is something
that is either produced or used by a project. Examples of artifacts produced by Maven for a project include:
JARs, source and binary distributions, and WARs.
• version:-It is the sub element of project. It specifies the version of the artifact under given group.
Note:-When no packaging is declared, Maven assumes the artifact is the default: jar.
Gradle
• Gradle is a build tool designed specifically to meet the requirements of building Java applications.
• Once it’s set up, building your application is as simple as running a single command on the command line or in
your IDE.
- gradlew build
• It includes, compiling, testing, and packaging your application, all with one command.
• To install Gradle on your own system (computer), go to the https://gradle.org/install/ and follow the
instructions there.
gradle init
• Here’s what Gradle created when we ran gradle init.
• build.gradle is the build script configuration file describing your application to Gradle so it can build it
• gradlew and gradlew.bat are known as the Gradle wrapper scripts, for Linux/Mac and Windows respectively.
These let you build an application without having to download and install Gradle like we did earlier. When the
wrapper is executed, it will automatically download Gradle and cache it locally. Normally you always build
your application with the wrapper, as it ensures it gets built with the correct version of Gradle.
• .gitignore configures Git so that the .gradle and build directories aren’t committed into version control.
Everything else gets committed though.
• The .gradle directory is a local cache managed by Gradle, and the build directory is where Gradle creates any
build outputs such as compiled Java code or jar files.
• Task: Gradle tasks are individual build actions you can run from the command line.
• Plugin: The last big concept to wrap your head around is the Gradle plugin. When you apply a plugin in your
build script, it automatically adds tasks to your project which you can run to achieve some particular outcome
Gradle wrapper
• The Gradle wrapper is a script you add to your Gradle project and use to execute your build.
• In an empty directory run gradle init to start the Gradle project setup wizard
• gradle-wrapper.jar code required for downloading the correct Gradle version when you run the build
• gradle-wrapper.properties file to configure the wrapper’s properties such as the Gradle version
• The four Gradle wrapper files described above are automatically created.
Gradle Vs Maven
Gradle Maven
2. Gradle is not driven by any xml file 2. Maven is driven by an xml file
3. Gradle works incrementally and gives a quicker 3. Maven does not take an incremental approach
build completion. and is slower in terms of build timings than
Gradle.
4. Gradle script is simple, not lengthy and can be 4. Maven has the xml file which is descriptive,
understood easily. lengthy
6. In Gradle, Java compilation is not a required step. 6. In Maven, compilation is a required step.
7. Gradle is a comparatively modern tool and its 7. Maven is a familiar tool and popular among the
users are limited in numbers. Java developers.
8. Numerous dependencies for the project can be 8. Numerous dependencies can be added to the
added in Gradle without the use of xml. project by adding them to the xml file (pom),
thereby making it more complex and difficult to
manage than Gradle.
• The key differences between Gradle and Maven are tabularized below
JUNIT
Software testing
• Software testing is meant to avoid software failure.
• A symptom is an observable behavior of the system that enables us to observe a failure and possibly find its
corresponding fault.
• The process of ensuring that the failure does not happen again is called fault correction, or fault removal.
• “testing can reveal only the presence of faults, never their absence.”
- Unit Testing, Integration Testing, Function Testing, Acceptance Testing, Installation Testing.
• At the day-to-day programming level, unit testing can easily be integrated in the programming effort by using
a Unit Testing Framework.
• However, unit testing cannot be applied for higher-level testing purposes such as function testing or
acceptance testing, which are system-level testing activities.
• A unit test is a piece of code written by a developer that exercises a very small, specific area of functionality
applied to one of the units of the code being tested. Usually a unit test exercises some particular method in a
particular context.
JUNIT
• In Java, the standard unit testing framework is known as JUnit.
• JUnit was created by Erich Gamma and Kent Beck, two authors best known for Design Patterns and eXtreme
Programming, respectively.
• Using JUnit you can easily and incrementally build a test suite that will help you measure your progress, spot
unintended side effects, and focus your development efforts.
• The JUnit test framework is a package of classes that lets you write tests for each method, then easily run
those tests
• To write test cases, you need to know and understand the Assert class
• Test Case – the testing of a class’s method against some specified conditions.
• Test Suite – a collection of test cases that can be tested in a single batch.
Writing a TestCase
• To start using JUnit, create a subclass of TestCase, to which you add test methods
import junit.framework.TestCase;
• This naming convention lets TestRunner automatically find your test classes
Assert methods
• Each assert method has parameters like these:
message, expected-value, actual-value
• Assert methods dealing with floating point numbers get an additional argument, a tolerance
• Each assert method has an equivalent version that does not take a message – however, this use is not
recommended because:
• List of different types of assertion statements that you can use to test your code
Example:
- These methods contain tests for the Counter methods increment(), decrement(), etc.
• This means you don’t have to worry about the order in which the tests are run
• Eclipse allows you to quickly create test case classes and test suite classes to write your test code in.
• With Eclipse, Test Driven Development (TDD), becomes very easy to organize and implement.
• Eclipse facilitates the testing by generating automatically stubs for testing class methods.
- Project → Properties → Build Path → Libraries → Add Library... → JUnit → JUnit 4/5… → Finish
• @BeforeAll: A static method in your test class that is called before all of its tests run.
• @AfterAll: A static method in your test class that is called after all of its tests run.
Lab Activity:
Exercise 38:
import org.junit.jupiter.api.*;
@BeforeAll
static void beforeAll() {
System.out.println("Connect to the database");
}
@BeforeEach
void beforeEach() {
System.out.println("Load the schema");
}
@AfterEach
void afterEach() {
System.out.println("Drop the schema");
}
@AfterAll
static void afterAll() {
System.out.println("Disconnect from the database");
}
@Test
void testOne() {
System.out.println("Test One");
}
@Test
void testTwo() {
System.out.println("Test Two");
}
}
• Tests are non-production code written in the same language as the application.
• Tests return a simple pass or fail, giving the developer immediate feedback
Why TDD?
A significant advantage of TDD is that it enables you to take small steps when writing software.
• Mostly written by developers using one of the tool specific to the application
TDD Lifecycle
1. Add a test.
2. Run all of your tests and observe the new test failing.
4. Run all of your tests and observe the new test succeeding.
What is Mockito?
• Mockito is a Java framework allowing the creation of mock objects in automated unit tests
Mock away external dependencies and insert the mocks into the code under test
Mockito Annotations
• @Mock is used for mock creation. It makes the test class more readable.
• The @Mock annotation is always used with @RunWith, a class-level annotation. We will see in detail how
both annotations are used to create and use a mock object in the next segment.
@Mock
ToDoService serviceMock;
• @InjectMocks is used to instantiate the tested object automatically and inject all
the @Mock or @Spy annotated field dependencies into it (if applicable).
• InjectMocks annotation is used to mock a class with all its dependencies. This is quite useful to test the
behavior completely.
@Mock
Map<String, String> Countries;
@InjectMocks
MyDictionary dic = new Continent();
@Test
public void UseInjectMocksAnnotation() {
Mockito.when(Countries.get("India")).thenReturn("asia");
assertEquals("asia", dic.getContinent("India"));
}
• @Spy is used to create a spy instance. We can use it instead spy(Object) method.
• Spy annotation is used to create a real object and spy on that real object. This would help to call all the object
methods while still tracking every interaction that is being mocked.
• Captor annotation is used to create an ArgumentCaptor instance to capture method argument values for
further assertions.
@Mock
HashMap<String, Integer> MyMap;
@Captor
ArgumentCaptor<String> keyCaptor;
@Captor
ArgumentCaptor<Integer> valueCaptor;
@Test
public void ArgumentCaptorTest()
{
hashMap.put("A", 10);
Mockito.verify(MyMap).put(keyCaptor.capture(), valueCaptor.capture());
assertEquals("A", keyCaptor.getValue());
assertEquals(new Integer(10), valueCaptor.getValue());
}
• To put it in other words, the function has no name, return type, or access modifiers (private, public, or
protected).
• Lambda expressions are available in other programming languages such as Python, Ruby, C#, and others
• It allows you to iterate over a collection, filter it, and retrieve data
• Syntax:
• Examples,
2. x -> x * x
3. ( ) -> x
• The first part is an argument list, which might have zero, one, or several arguments and is wrapped by
parenthesis.
• The second part is the Arrow-Token (->), which connects the list of arguments to the expression body
• The method body, which contains expressions and statements for lambda expression, is the third part
• forEach is a method that takes as input a function and calls the function for each value on the list
• Note the absence of type declarations in the lambda; the Java 8 compiler does type inference
• Braces are not needed for single-line lambdas (but could be used if desired).
• x -> System.out.println(x) is a lambda expression that defines an anonymous function with one parameter
named x of type Integer
Multiline lambda
• Braces are needed to enclose a multiline body in a lambda expression.
intSeq.forEach(x -> {
x += 2;
System.out.println(x);
});
intSeq.forEach(x -> {
int y = x * 2;
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
System.out.println(y);
});
intSeq.forEach((Integer x -> {
x += 2;
System.out.println(x);
});
• For example,
System.out.println(x);
Functional Interfaces
• Design decision: Java 8 lambdas are assigned to functional interfaces.
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
• A functional interface is a Java interface with exactly one non-default method. E.g.,
Example
• Here is an interface called Consumer with a single method called accept.
• The forEach method iterates through the items in the object Consumer and performs the action accept on
each item.
• The lambda expression becomes the body of the function in the interface.
• The signature of the function is defined by the interface.
• The type is the same as that of the functional interface to which the lambda expression is assigned
• The lambda expression becomes the body of the method in the interface
• Any interface with only one nondefault method is considered a functional interface by Java 8.
• So functional interfaces are Java 8’s secret sauce for backward compatibility.
• Note: local variables used inside the body of a lambda must be final or effectively final
Method References
• Method references can be used to pass an existing function in places where a lambda is expected
• The signature of the referenced method needs to match the signature of the functional interface method
intSeq.forEach(System.out::println);
• Notice the double colons :: . These signal to the Java compiler that this is a method reference. The method
referenced is what comes after the double colons. Whatever class or object that owns the referenced method
comes before the double colons.
Default Methods
• Java 8 uses lambda expressions and default methods in conjunction with the Java collections framework to
achieve backward compatibility with existing published interfaces
• We need default methods because, for example, the Collections interface has no stream() method and we'd
like to use existing Collections interfact to stream.
Stream API
• One of the major new features in Java 8 is the introduction of the stream functionality – java.util.stream –
which contains classes for processing sequences of elements.
• The central API class is the Stream<T>. The following section will demonstrate how streams can be created
using the existing data-provider sources.
• Streams are useful for selecting values and performing actions on the results.
Stream Operations
• There are many useful operations that can be performed on a stream.
• They are divided into intermediate operations (return Stream<T>) and terminal operations (return a result of
definite type). Intermediate operations allow chaining.
• It's also worth noting that operations on streams don't change the source.
• An intermediate operation keeps a stream open for further operations. Intermediate operations are lazy.
• A terminal operation must be the final operation on a stream. Once a terminal operation is invoked, the
stream is consumed and is no longer usable.
• They are lazily loaded and will only be executed if you include a terminal operation at the end.
• The filter() method allows us to pick a stream of elements that satisfy a predicate.
• To convert elements of a Stream by applying a special function to them and to collect these new elements into
a Stream, we can use the map() method
• They are eagerly loaded and will cause the entire pipeline to be executed.
Stream Pipeline
To perform a sequence of operations over the elements of the data source and aggregate their results, we need three
parts: the source, intermediate operation(s) and a terminal operation.
3. A terminal operation
Example1
Example2
Using lambdas and stream to sum the squares of the elements on a list
Here map(x -> x*x) squares each element and then reduce((x,y) -> x + y) reduces all elements into a single number
Commenting
• Commenting is necessary for maintaining any program
• Without commenting, the program is not complete
• Do not assume that the other person who reads this program will understand it clearly
• If commenting is not done at the beginning, it is forgotten.
• Program - a physical file – you need to comment the following at the top.
- at the top of the program - header comment
- what the program achieves
- who coded on what day
• Classes
- Comment at the beginning of the class about what the class does
- class Employee
- // this class is used to manage all information
- // about employees and retrieve specific data
• Methods within classes
- what this method/function/procedure does
- what are the parameters and their purpose
- what are the return values
• Comment before every loop.
• Comment before every file or database operation
• Comment before every if condition
Naming Conventions
• Readability improves understanding; that further improves maintainability
• If programs are not consistent, maintenance is tough
• If 20 developers work in a project and each one names functions in the way he/she wants, will the client
approve the same?
• We must have a document on naming conventions
• Every document must be named properly and it must be stored in a proper folder.
• You need to have a convention for naming
- Programs
- Classes
- Methods
- Variables
- Labels in programs
- Reusable library functions
Modularity of code
• Modularity is important for easy maintenance
• Fixes done on modular programs are easy to isolate from other regression effects
• If this is not checked, it can run forever, infinitely and can bring down the server
• Loop Sample
Participant Guide By EduBridge Learning Pvt. Ltd
All rights reserved.
No part of this document may be reproduced in any material form(including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.
– gateway 1 // variables, flags
– xyz = 10
– ..
– logic
– ... gateway 3
– gateway 4
• Gateways are the check posts where we must watch the value of the variables, loop counters and loop flags
• Ensure proper resetting of flags and counters and check their values and gateways of the loops
• Never instantiate a class inside a loop; if needed, close it within the loop
Exceptions
• Issues may be caused by programmer
– database is down
– connections exhausted
3. Memory
Performance
• We need to monitor cpu, memory, network
• Memory is directly related to variables and object – do not declare huge arrays or objects
• Any database operations, open late and close the connection early.
• Any memory allocated must be freed – else the program will shut down after some time
• Any object instantiated must be released – else system will be depleted of memory and hence performance
will come down
Program Logic
• Usually the logic design will be provided to the developer
• If it is not provided, take 30 minutes and write the logic of the program in English first
• Get the logic approved by the team lead and then start coding
• Developers usually feel that this takes time; but it reduces the time effectively while coding and reworking
• Since developers are not used to documenting, they feel it is not their job. Hence they miss a lot of finer points
• If you write the logic first, you will get a lot of clarifications at that time itself and hence the code will come out
clean
participants to complete the exercise given in the SoloLearn App and share the respective certificates with the
trainers.