Unit-1 (Java Introduction)
Unit-1 (Java Introduction)
Unit: I
1
Content
❖ Course Objective
❖ Course Outcomes
❖ CO-PO Mapping
❖ CO-PSO Mapping
❖ Syllabus
❖ Prerequisite
❖ Basic Concept of OOPS
2
Content
❖ Design Strategies
❖ Software Measurement and Metrics
❖ Cyclomatic Complexity Measures
❖ Video Links
❖ Daily Quiz
❖ Weekly Assignment
❖ MCQ
❖ Old Question Papers
❖ Expected Questions for University Exam
❖ Summary
❖ References
3
Syllabus
Unit TOPIC
Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File Structure, and
Compilation. Fundamental,
Programming Structures in Java: Defining Classes in Java, Constructors, Methods, Access Specifies,
Static Members, Final Members, Comments, Data types, Variables, Operators, Control Flow, Arrays &
I String.
Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class, Overriding,
Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract Class.
Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for Library
Packages, Import and Static Import Naming Convention For Packages
Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of Exception, Control Flow
in Exceptions, JVM Reaction to Exceptions, Use of try, catch, finally, throw, throws in Exception
Handling, In-built and User Defined Exceptions, Checked and Un-Checked Exceptions.
II Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java.
Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread Priorities, Synchronizing Threads,
Inter-thread Communication.
Java New Features: Functional Interfaces, Lambda Expression, Method References, Stream API, Default
Methods, Static Method, Base64 Encode and Decode, For Each Method, Try-with resources, Type
III Annotations, Repeating Annotations, Java Module System, Diamond Syntax with 08 Inner Anonymous
Class, Local Variable Type Inference, Switch Expressions, Yield Keyword, TextBlocks, Records, Sealed
Classes
4
Syllabus
Unit TOPIC
Java Collections Framework: Collection in Java, Collection Framework in Java, Hierarchy of
Collection Framework, Iterator Interface, Collection Interface, List Interface, ArrayList, LinkedList,
IV Vector, Stack, Queue Interface, Set Interface, HashSet, LinkedHashSet, SortedSet Interface,
TreeSet, Map Interface, HashMap Class, LinkedHashMap Class, TreeMap Class, Hashtable Class,
Sorting, Comparable Interface, Comparator Interface, Properties Class in Java.
Spring Framework: Spring Core Basics-Spring Dependency Injection concepts, Spring Inversion of
Control, AOP, Bean Scopes- Singleton, Prototype, Request, Session, Application, Web Socket,
Auto wiring, Annotations, Life Cycle Call backs, Bean Configuration styles Spring Boot: Spring
V Boot Build Systems, Spring Boot Code Structure, Spring Boot Runners, Logger, BUILDING
RESTFUL WEB SERVICES, Rest Controller, Request Mapping, Request Body, Path Variable,
Request Parameter, GET, POST, PUT, DELETE APIs, Build Web Applications
5
Course Outcome
Bloom’s
Course Outcomes (CO) Knowledge
Level (KL)
CO2 Implement exception handling, file handling, and multi-threading in Java K2, K4
Test web and RESTful Web Services with Spring Boot using Spring
CO5 K5
Framework concepts
6
CO-PO Mapping
1 2 3 4 5 6 7 8 9 10 11 12 1 2
CO 1 2 2 2 2 2 - - - - - - 2 2 -
CO 2 2 2 2 2 2 - - - - - - 2 2 -
CO 3 2 3 2 2 2 - - - - - - 2 2 -
CO 4 2 3 2 2 3 - - - - - 2 2 2 -
CO 5 1 3 2 3 3 - - - - - 2 3 3 -
7
CO-PO and PSO Mapping
8
Prerequisite and Recap
• Innovative Thinking.
9
Evaluation Scheme
2 1 4 20 10 30 70 100 3
10
PO’s
PO2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations
PO4. Conduct investigations of complex problems: Use research- based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
• understanding of the limitations
11
PO’s
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
12
PO’s
PO12. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
13
Brief Introduction about the Subject with Videos
14
Why JAVA/History of JAVA
15
Cont…
16
17
18
19
.
20
.
21
.
22
JVM(Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the JVM: specification,
implementation, and instance.
23
JAVA Runtime Environment(JRE)
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a
set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
24
Java Development Kit (JDK)
JRE
JVM
Library
Classes
Development Tools
25
Java Source File Structure
Java source file structure describes that the Java source code file
must follow a schema or structure. In this article, we will see
some of the important guidelines that a Java program must
follow.
27
Java Source File Structure
Working with Java Source File
28
Compilation and Execution of a
Java Program
Java, being a platform-independent programming language, doesn’t work on the
one-step compilation. Instead, it involves a two-step execution, first through an OS-
independent compiler; and second, in a virtual machine (JVM) which is custom-built
for every operating system.
29
Java Fundamentals
Java main() Method – public static void main(String[]
args)
Java’s main() method is the starting point from where the JVM starts the
execution of a Java program. JVM will not execute the code, if the program
is missing the main method. Hence, it is one of the most important
methods of Java, and having a proper understanding of it is very important.
The Java compiler or JVM looks for the main method when it starts
executing a Java program. The signature of the main method needs to be in
a specific way for the JVM to recognize that method as its entry point. If we
change the signature of the method, the program compiles but does not
execute.
The execution of the Java program, the java.exe is called. The Java.exe in
turn makes Java Native Interface or JNI calls, and they load the JVM. The
java.exe parses the command line, generates a new String array, and
invokes the main() method. By default, the main thread is always a non-
daemon thread.
30
Java Fundamentals
Java main() Method – public static void main(String[]
args)
31
Java Fundamentals
Java main() Method – public static void main(String[] args)
1. Public
It is an Access modifier, which specifies from where and who can
access the method. Making the main() method public makes it
globally available. It is made public so that JVM can invoke it from
outside the class as it is not present in the current class.
2. Static
It is a keyword that is when associated with a method, making it
a class-related method. The main() method is static so that JVM can
invoke it without instantiating the class. This also saves the
unnecessary wastage of memory which would have been used by the
object declared only for calling the main() method by the JVM.
32
Java Fundamentals
Java main() Method – public static void main(String[] args)
3. Void
It is a keyword and is used to specify that a method doesn’t
return anything. As the main() method doesn’t return anything, its
return type is void. As soon as the main() method terminates, the
Java program terminates too. Hence, it doesn’t make any sense to
return from the main() method as JVM can’t do anything with its
return value of it.
4. main
It is the name of the Java main method. It is the identifier that
the JVM looks for as the starting point of the Java program. It’s
not a keyword.
If we change the name while initiating main method, we will get an
error.
33
Java Fundamentals
Java main() Method – public static void main(String[] args)
5. String[] args
It stores Java command-line arguments and is an array of
type java.lang.String class. Here, the name of the String array
is args but it is not fixed and the user can use any name in place of
it.
34
Java Fundamentals
System.out.println in Java
Java System.out.println() is used to print an argument that is passed to
it.
Parts of System.out.println()
The statement can be broken into 3 parts which can be understood
separately:
1.System: It is a final class defined in the java.lang package.
2.out: This is an instance of PrintStream type, which is a public and static
member field of the System class.
3.println(): As all instances of the PrintStream class have a public method
println(), we can invoke the same on out as well. This is an upgraded
version of print(). It prints any argument passed to it and adds a new line
to the output. We can assume that System.out represents the Standard
Output Stream.
35
Java Fundamentals
System.out.println in Java
36
History of Java
History of Java
The history of Java is very interesting. Java was originally designed
for interactive television, but it was too advanced technology for
the digital cable television industry at the time. The history of Java
starts with the Green Team. Java team members (also known as
Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best
suited for internet programming. Later, Java technology was
incorporated by Netscape.
37
History of Java
History of Java
The principles for creating Java programming were "Simple,
Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices,
games, e-business solutions, etc. Following are given significant
points that describe the history of Java.
38
History of Java
History of Java
1) James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in
electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and
the file extension was .gt.
4) After that, it was called Oak and was developed as a part of
the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a
national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
39
History of Java
History of Java
6) In 1995, Oak was renamed as "Java" because it was
already a trademark by Oak Technologies.
7) Initially developed by James Gosling at Sun
Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
8) In 1995, Time magazine called Java one of the Ten Best
Products of 1995.
9) JDK 1.0 was released on January 23, 1996. After the first
release of Java, there have been many additional features
added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in
Java.
40
History of Java
Java Version History
42
Features of Java
Java is an object-oriented programming
language. Everything in Java is an object.
Object-oriented means we organize our
software as a combination of different types of
objects that incorporate both data and behavior.
43
Features of Java
Simple
Java is very easy to learn, and its syntax is simple, clean and
easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:
•Java syntax is based on C++ (so easier for programmers to
learn it after C++).
•Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator overloading,
etc.
•There is no need to remove unreferenced objects because
there is an Automatic Garbage Collection in Java.
44
Features of Java
Secure
Java is best known for its security. With Java, we can
develop virus-free systems. Java is secured because:
•No explicit pointer
•Java Programs run inside a virtual machine
sandbox
45
Features of Java
Platform Independent
Robust
The English mining of Robust is strong. Java is
robust because:
•It uses strong memory management.
•There is a lack of pointers that avoids security
problems.
•Java provides automatic garbage collection which
runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application
anymore.
•There are exception handling and the type checking
mechanism in Java. All these points make Java
robust.
47
Features of Java
Portable
Java is portable because it facilitates you to
carry the Java bytecode to any platform. It
doesn't require any implementation.
48
Features of Java
Architecture-neutral
Java is architecture neutral because there are no
implementation dependent features, for example,
the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes
of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
49
Features of Java
Dynamic
Java is a dynamic language. It supports the
dynamic loading of classes. It means classes
are loaded on demand. It also supports
functions from its native languages, i.e., C and
C++.
50
Features of Java
Interpreted
Java uses both compiler and interpreter. Java
source code is converted into bytecode at
compilation time. The interpreter executes this
bytecode at runtime and produces output.
Java is interpreted that is why it is platform-
independent.
51
Features of Java
High-performance
Java is faster than other traditional interpreted
programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than
a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
52
Features of Java
Multi-threaded
A thread is like a separate program, executing
concurrently. We can write Java programs that deal
with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for
multi-media, Web applications, etc.
53
Features of Java
Distributed
Java is distributed because it facilitates users to
create distributed applications in Java. RMI (Remote
Method Invocation) and EJB (Enterprise Server
Bean) are used for creating distributed applications.
This feature of Java makes us able to access files by
calling the methods from any machine on the
internet.
54
Defining Classes in Java
55
Defining Classes in Java
Create a Class
To create a class, use the keyword class:
class MyClass
{ // field, constructor, and
// method declarations }
This is a class declaration. The class body (the area between the
braces) contains all the code that provides for the life cycle of the
objects created from the class:
constructors for initializing new objects,
fields provide the state of the class and its objects, and
methods to implement the behavior of the class and its objects.
57
Defining Classes in Java
Create a Class
To create a class, use the keyword class:
class MyClass
{ // field, constructor, and
// method declarations }
This is a class declaration. The class body (the area between the
braces) contains all the code that provides for the life cycle of the
objects created from the class:
constructors for initializing new objects,
fields provide the state of the class and its objects, and
methods to implement the behavior of the class and its objects.
58
Defining Classes in Java
When no access modifier is specified for a class, method, or data member – It is said to be
having the default access modifier by default. The data members, classes, or methods that
are not declared using any access modifiers i.e. having default access modifiers are
accessible only within the same package.
60
Declaring Member Variables in
Java
Field declarations are composed of three components, in
order:
1.Zero or more modifiers, such as public or private.
2.The field's type.
3.The field's name.
61
Methods in Java
The method in Java or Methods of Java is a collection of statements that
perform some specific task and return the result to the caller. A Java
method can perform some specific task without returning anything. Java
Methods allow us to reuse the code without retyping the code. In Java,
every method must be part of some class that is different from languages
like C, C++, and Python.
1. A method is like a function i.e. used to expose the behavior of an object
2. It is a set of codes that perform a particular task.
62
Methods in Java
63
Methods in Java
More generally, method declarations have six components, in order:
1.Modifiers—such as public, private, and others you will learn about later.
2.The return type—the data type of the value returned by the method,
or void if the method does not return a value.
3.The method name—the rules for field names apply to method names as
well, but the convention is a little different.
4.The parameter list in parenthesis—a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty parentheses.
5.An exception list—to be discussed later.
6.The method body, enclosed between braces {} —the method's code,
including the declaration of local variables, goes here.
64
Methods in Java
65
Methods in Java
2. The return type: The data type of the value returned by the
method or void if does not return a value. It is Mandatory in
syntax.
3. Method Name: the rules for field names apply to method
names as well, but the convention is a little different. It
is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input
parameters is defined, preceded by their data type, within the
enclosed parenthesis. If there are no parameters, you must use
empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can
throw, you can specify these exception(s). It is Optional in
syntax.
6. Method body: it is enclosed between braces. The code you
need to be executed to perform your intended operations. It
is Optional in syntax.
66
Methods in Java
67
Methods in Java
68
Class in Java
69
Class in Java
The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it.
70
Class in Java
mybox as a reference to an
object of type Box
71
Constructor in Java
new operator dynamically allocates memory for an object.
The class name followed by parentheses
class-var = new classname ( ); specifies the constructor for the class.
72
Constructors in Java
Java Constructors
Java constructors or constructors in Java is a
terminology used to construct something in our
programs. A constructor in Java is a special
method that is used to initialize objects. The
constructor is called when an object of a class is
created. It can be used to set initial values for
object attributes.
73
Constructors in Java
74
Constructors in Java
75
Constructors in Java
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A
default constructor is invisible. And if we write a constructor with no
arguments, the compiler does not create a default constructor. It is taken out. It
is being overloaded and called a parameterized constructor. The default
constructor changed into the parameterized constructor. But Parameterized
constructor can’t change the default constructor.
import java.io.*;
// Driver class
class GFG {
// Default Constructor
GFG() { System.out.println("Default constructor"); }
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
} 76
Constructors in Java
78
Constructors in Java
// Java Program for Copy Constructor
import java.io.*;
80
Access Specifiers in Java
1) Private
The private access modifier is accessible only within the
class.
82
Access Specifiers in Java
3) Protected
The protected access modifier is accessible within package and
outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
83
Output:Hello
Access Specifiers in Java
3) Public
The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
84
static in Java
86
static in Java
87
static in Java
88
static in Java
89
final in Java
90
final in Java
91
final in Java
Final member
92
final in Java
Final method
93
final in Java
Final method
94
Input from user in Java
To input integer value
95
Input from user in Java
To input a character
96
Variables in Java
97
Variables in Java
98
Variables in Java
99
Operators in Java
Operators constitute the basic building block to any programming language.
Java too provides many types of operators which can be used according to the
need to perform various calculations and functions, be it logical, arithmetic,
relational, etc. They are classified based on the functionality they provide.
1.Arithmetic Operators
2.Unary Operators
3.Assignment Operator
4.Relational Operators
5.Logical Operators
6.Ternary Operator
7.Bitwise Operators
8.Shift Operators
100
Operators in Java
Arithmetic Operators
These operators involve the mathematical operators that can be used to perform
various simple or advanced arithmetic operations on the primitive data types
referred to as the operands. These operators consist of various unary and binary
operators that can be applied on a single or two operands.
101
Operators in Java
Unary Operators
102
Operators in Java
Assignment Operators
These operators are used to assign values to a variable. The left side
operand of the assignment operator is a variable, and the right side
operand of the assignment operator is a value. The value on the right
side must be of the same data type of the operand on the left side.
1. Simple Assignment Operator: =
2. Compound Assignment Operator:
(+=) operator:
(-=) operator
(*=) operator
(/=) operator
(%=) operator
103
Operators in Java
104
Operators in Java
1.AND Operator ( && ) – if( a && b ) [if true execute else don’t]
2.OR Operator ( || ) – if( a || b) [if one of them is true to execute else
don’t]
3.NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
105
Operators in Java
106
Operators in Java
107
Operators in Java
108
Operators in Java
Bitwise Operators
Bitwise operators are used to performing the manipulation of
individual bits of a number. They can be used with any integral
type (char, short, int, etc.). They are used when performing update
and query operations of the Binary indexed trees.
Bitwise OR (|)
109
Operators in Java
Bitwise Operators
Bitwise operators are used to performing the manipulation of
individual bits of a number. They can be used with any integral
type (char, short, int, etc.). They are used when performing update
and query operations of the Binary indexed trees.
Bitwise OR (|)
Bitwise AND (&)
Bitwise XOR (^)
Bitwise Complement (~)
110
Operators in Java
Bitwise Operators
Bit-Shift Operators (Shift Operators)
Shift operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively. They
can be used when we have to multiply or divide a number by two.
111
Control Flow in Java
112
Control Flow in Java
Decision-Making statements:
113
Control Flow in Java
Decision-Making statements:
114
Control Flow in Java
Decision-Making statements:
Nested if-statement
115
Control Flow in Java
Switch Statement:
Switch statements are similar to if-
else-if statements. The switch
statement contains multiple blocks
of code called cases and a single
case is executed based on the
variable which is being switched.
116
Control Flow in Java
Loop Statements
In programming, sometimes we need to execute the block of code
repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a
particular condition.
117
Control Flow in Java
118
Control Flow in Java
119
Control Flow in Java
Java for-each loop
Java provides an enhanced for loop to traverse the data structures
like array or collection. In the for-each loop, we don't need to update
the loop variable.
120
Control Flow in Java
Java for-each loop
Output:
121
Control Flow in Java
Java while loop
The while loop is also used to iterate over the number of statements
multiple times. However, if we don't know the number of iterations in
advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the
loop statement in while loop.
122
Control Flow in Java
Java while loop
123
Control Flow in Java
Java do-while loop
The do-while loop checks the condition at the end of the loop after
executing the loop statements. When the number of iteration is not
known and we have to execute the loop at least once, we can use
do-while loop.
It is also known as the exit-controlled loop since the condition is not
checked in advance. The syntax of the do-while loop is given below.
124
Control Flow in Java
Java do-while loop
125
Control Flow in Java
Jump Statements
Jump statements are used to transfer the control of the program to
the specific statements. In other words, jump statements transfer the
execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
126
Control Flow in Java
127
Control Flow in Java
Java continue statement
Unlike break statement, the continue statement doesn't break the
loop, whereas, it skips the specific part of the loop and jumps to the
next iteration of the loop immediately.
128
Arrays in Java
Java Arrays
Normally, an array is a collection of similar type of elements which
has contiguous memory location.
Java array is an object which contains elements of a similar data
type. Additionally, The elements of an array are stored in a
contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a
Java array.
Array in Java is index-based, the first element of the array is stored
at the 0th index, 2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length
member. In C/C++, we need to use the sizeof operator.
129
Arrays in Java
Advantages
•Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.
•Random access: We can get any data located at an index
position.
Disadvantages
•Size Limit: We can store only the fixed size of elements in the
array. It doesn't grow its size at runtime. To solve this problem,
collection framework is used in Java which grows130
Arrays in Java
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
131
Arrays in Java
Single Dimensional Array in
Java
132
Arrays in Java
Single Dimensional Array in
Java
133
Arrays in Java
134
Arrays in Java
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-
each loop prints the array elements one by one. It holds an array
element in a variable, then executes the body of the loop.
135
Arrays in Java
136
Arrays in Java
Multidimensional Array in Java
In such case, data is stored in row and column based index (also
known as matrix form).
Syntax to Declare Multidimensional Array in Java
1.dataType[][] arrayRefVar; (or)
2.dataType [][]arrayRefVar; (or)
3.dataType arrayRefVar[][]; (or)
4.dataType []arrayRefVar[];
137
Arrays in Java
Multidimensional Array in Java
138
Arrays in Java
Addition of 2 Matrices in Java
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
140
Arrays in Java
Multiplication of 2 Matrices in
Java
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
141
Strings in Java
Java String
Generally, String is a sequence of characters. But in Java, string is
an object that represents a sequence of characters. The
java.lang.String class is used to create a string object.
For example:
char[] ch={‘r',’k',’g',’i','t',’g',’h',’a',’z’,’i’,’a’,’b’,’a’,’d’};
String s=new String(ch);
is same as:
String s=“rkgitghaziabad";
142
Strings in Java
Java String
143
Inheritance in Java
144
Inheritance in Java
146
Inheritance in Java
147
Inheritance in Java
148
Inheritance in Java
149
Inheritance in Java
150
Inheritance in Java
Multilevel Inheritance Example
151
Inheritance in Java
Hierarchical Inheritance
Example
152
Inheritance in Java
Multiple inheritance is not supported in java?
153
Method Overloading in Java
Method Overloading in Java
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of
the methods increases the readability of the program.
154
Method Overloading in Java
1) Method Overloading: changing no. of arguments
155
Method Overloading in Java
2) Method Overloading: changing data type of arguments
156
Method Overloading in Java
Method Overloading is not possible by changing the return type
of method only
157
Method Overriding in Java
If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
In other words, If a subclass provides the specific implementation of
the method that has been declared by one of its parent class, it is
known as method overriding.
Usage of Java Method Overriding
•Method overriding is used to provide the specific implementation
of a method which is already provided by its superclass.
•Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1.The method must have the same name as in the parent class
2.The method must have the same parameter as in the parent
class.
3.There must be an IS-A relationship (inheritance).
158
Method Overriding in Java
160
Method Overriding in Java
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
161
Method Overriding in Java
162
Method Overriding in Java
163
Difference between Overlaoding &
Overriding in Java
164
Encapsulation in Java
165
Encapsulation in Java
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the
class read-only or write-only. In other words, you can skip the
getter or setter methods.
It provides you the control over the data. Suppose you want to set
the value of id which should be greater than 100 only, you can write
the logic inside the setter method. You can write the logic not to
store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will
not be able to access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters
and setters. So, it is easy and fast to create an encapsulated
class in Java.
166
Encapsulation in Java
Advantage of Encapsulation in Java
It provides you the control over the data. Suppose you want to set
the value of id which should be greater than 100 only, you can write
the logic inside the setter method. You can write the logic not to
store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will
not be able to access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters
and setters. So, it is easy and fast to create an encapsulated
class in Java.
167
Encapsulation in Java
Achieving Encapsulation in Java
To achieve encapsulation in Java −
168
Encapsulation in Java
public class EncapTest {
private String name;
private String idNum;
private int age;
169
Encapsulation in Java
170
Encapsulation in Java
package com.javatpoint;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}
172
Abstraction in Java
Abstraction is a feature of OOPs. The feature allows us to hide the
implementation detail from the user and shows only the
functionality of the programming to the user. Because the user is
not interested to know the implementation. It is also safe from the
security point of view.
The best example of abstraction is a car. When we derive a car, we
do not know how is the car moving or how internal components
are working? But we know how to derive a car. It means it is not
necessary to know how the car is working, but it is important how to
derive a car. The same is an abstraction.
173
Abstraction in Java
174
Abstraction in Java
175
Abstraction in Java
176
Abstraction in Java
//abstract class
abstract class Demo
{
//abstract method
abstract void display(); }
//extends the abstract class
public class MainClass extends Demo
{
//defining the body of the method of the abstract class
void display() {
System.out.println("Abstract method called.");
}
public static void main(String[] args)
{
MainClass obj = new MainClass ();
//invoking abstract method
obj.display();
}
177
}
Interface in Java
An interface in Java is a blueprint of a class. It has static constants
and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There
can be only abstract methods in the Java interface, not method
body. It is used to achieve abstraction and multiple inheritance in
Java.
In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.
Why use Java interface?
There are mainly three reasons to use interface. They are given
below.
•It is used to achieve abstraction.
•By interface, we can support the functionality of multiple
inheritance.
178
Interface in Java
Interface
Class
Inherits
Smart Phone
179
Interface in Java
Using Interface
In Java, an interface is similar to Java classes. The difference is only
that an interface contains empty methods (methods that do not have
method implementation) and variables. In other words, it is a
collection of abstract methods (the method that does not have a
method body) and static constants. The important point about an
interface is that each method is public and abstract and does not
contain any constructor. Along with the abstraction, it also helps to
achieve multiple inheritance. The implementation of these methods
provided by the clients when they implement the interface.
180
Interface in Java
181
Interface in Java
Features of Interface:
•We can achieve total abstraction.
•We can use multiple interfaces in a class that leads to multiple
inheritance.
•It also helps to achieve loose coupling.
182
Interface in Java
183
Interface in Java
Interface fields are public, static and final by default, and the
methods are public and abstract.
184
Interface in Java
Car.java
interface CarStart
{ void start(); }
interface CarStop
{ void stop(); }
public class Car implements CarStart, CarStop
{ public void start()
{ System.out.println("The car engine has been started."); }
public void stop()
{ System.out.println("The car engine has been stopped."); }
public static void main(String args[])
{
Car c = new Car();
c.start();
c.stop(); }
}
185
Interface in Java
Difference Between Class and Interface
186
Abstract Class in Java
187
Abstract Class in Java
188
Abstract Class in Java
189
Abstract Class in Java
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() { // The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
} 190
}
Packages in Java
A java package is a group of similar types of classes, interfaces and
sub-packages.
Package in java can be categorized in two form, built-in package and
user-defined package.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
191
Packages in Java
192
Packages in Java
193
Packages in Java
194
Packages in Java
How to access package from another package?
There are three ways to access the package from outside the
package.
1.import package.*;
2.import package.classname;
3.fully qualified name.
195
Packages in Java
1) Using packagename.*
If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of
another package accessible to the current package.
//save by A.java //save by B.java
package pack; package mypack;
public class A{ import pack.*;
public void msg()
{System.out.println("Hello");} class B{
} public static void main(String ar
gs[]){
A obj = new A();
obj.msg();
}
}
196
Packages in Java
2)Using packagename.classname
//save by A.java //save by B.java
package mypack;
package pack; import pack.A;
public class A{
public void msg() class B{
{System.out.println("Hello");} public static void main(String ar
} gs[]){
A obj = new A();
obj.msg();
}
}
197
Packages in Java
3) Using fully qualified name
198
Static import in Java
In Java, static import concept is introduced in 1.5 version. With the
help of static import, we can access the static members of a class
directly without class name or any object. For Example: we always use
sqrt() method of Math class by using Math class i.e. Math.sqrt(), but
by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability
and enhance coding. But according to the programming experts, it
will lead to confusion and not good for programming. If there is no
specific requirement then we should not go for static import.
199
Static import in Java
200
Static import in Java
201
Static import in Java
// Java to illustrate calling of static member of
// System class without Class name
import static java.lang.Math.*;
import static java.lang.System.*;
class Geeks {
public static void main(String[] args)
{
// We are calling static member of System class
// directly without System class name
out.println(sqrt(4));
out.println(pow(2, 2));
out.println(abs(6.3));
}
}
202
Static import in Java
Ambiguity in static import:
If two static members of the same name are imported from multiple
different classes, the compiler will throw an error, as it will not be able
to determine which member to use in the absence of class name
qualification.
203