This document provides an overview of key concepts in Java programming including classes, methods, variables, data types, control flow statements, and arrays. It explains the structure and purpose of a basic Java class, describes Java's primitive data types and how to declare variables, and gives examples of if/else, for loops, and one-dimensional arrays. The summary covers the core elements needed to understand basic Java programs.
In this you learn about Control Statements
1. Selection Statements
i. If
ii. If-else
iii. Nested-if
iv. If-Elseif ladder
2. Looping Statements
i. while loop
ii. do-while loop
iii. For loop
3. Jumping Statements
i. break
ii. continue
iii return
In this you learn about Control Statements
1. Selection Statements
i. If
ii. If-else
iii. Nested-if
iv. If-Elseif ladder
2. Looping Statements
i. while loop
ii. do-while loop
iii. For loop
3. Jumping Statements
i. break
ii. continue
iii return
Decision Making in Java (if, if-else, switch, break, continue, jump) Decision Making in programming is similar to decision making in real life. A programming language uses control statements to control the flow of execution of program based on certain conditions.
Mahika Tutorials sharing PPT slide for core java programming language. Go threw this slide and visit our YouTube page too
https://www.youtube.com/c/mahikatutorials
Java is a high-level programming language developed by Sun Microsystems. ... Instead, Java programs are interpreted by the Java Virtual Machine, or JVM, which runs on multiple platforms. This means all Java programs are multiplatform and can run on different platforms, including Macintosh, Windows, and Unix computers.
Decision Making in Java (if, if-else, switch, break, continue, jump) Decision Making in programming is similar to decision making in real life. A programming language uses control statements to control the flow of execution of program based on certain conditions.
Mahika Tutorials sharing PPT slide for core java programming language. Go threw this slide and visit our YouTube page too
https://www.youtube.com/c/mahikatutorials
Java is a high-level programming language developed by Sun Microsystems. ... Instead, Java programs are interpreted by the Java Virtual Machine, or JVM, which runs on multiple platforms. This means all Java programs are multiplatform and can run on different platforms, including Macintosh, Windows, and Unix computers.
NIDM (National Institute Of Digital Marketing) Bangalore Is One Of The Leading & best Digital Marketing Institute In Bangalore, India And We Have Brand Value For The Quality Of Education Which We Provide.
www.nidmindia.com
The Impact of Artificial Intelligence on Modern Society.pdfssuser3e63fc
Just a game Assignment 3
1. What has made Louis Vuitton's business model successful in the Japanese luxury market?
2. What are the opportunities and challenges for Louis Vuitton in Japan?
3. What are the specifics of the Japanese fashion luxury market?
4. How did Louis Vuitton enter into the Japanese market originally? What were the other entry strategies it adopted later to strengthen its presence?
5. Will Louis Vuitton have any new challenges arise due to the global financial crisis? How does it overcome the new challenges?Assignment 3
1. What has made Louis Vuitton's business model successful in the Japanese luxury market?
2. What are the opportunities and challenges for Louis Vuitton in Japan?
3. What are the specifics of the Japanese fashion luxury market?
4. How did Louis Vuitton enter into the Japanese market originally? What were the other entry strategies it adopted later to strengthen its presence?
5. Will Louis Vuitton have any new challenges arise due to the global financial crisis? How does it overcome the new challenges?Assignment 3
1. What has made Louis Vuitton's business model successful in the Japanese luxury market?
2. What are the opportunities and challenges for Louis Vuitton in Japan?
3. What are the specifics of the Japanese fashion luxury market?
4. How did Louis Vuitton enter into the Japanese market originally? What were the other entry strategies it adopted later to strengthen its presence?
5. Will Louis Vuitton have any new challenges arise due to the global financial crisis? How does it overcome the new challenges?
Want to move your career forward? Looking to build your leadership skills while helping others learn, grow, and improve their skills? Seeking someone who can guide you in achieving these goals?
You can accomplish this through a mentoring partnership. Learn more about the PMISSC Mentoring Program, where you’ll discover the incredible benefits of becoming a mentor or mentee. This program is designed to foster professional growth, enhance skills, and build a strong network within the project management community. Whether you're looking to share your expertise or seeking guidance to advance your career, the PMI Mentoring Program offers valuable opportunities for personal and professional development.
Watch this to learn:
* Overview of the PMISSC Mentoring Program: Mission, vision, and objectives.
* Benefits for Volunteer Mentors: Professional development, networking, personal satisfaction, and recognition.
* Advantages for Mentees: Career advancement, skill development, networking, and confidence building.
* Program Structure and Expectations: Mentor-mentee matching process, program phases, and time commitment.
* Success Stories and Testimonials: Inspiring examples from past participants.
* How to Get Involved: Steps to participate and resources available for support throughout the program.
Learn how you can make a difference in the project management community and take the next step in your professional journey.
About Hector Del Castillo
Hector is VP of Professional Development at the PMI Silver Spring Chapter, and CEO of Bold PM. He's a mid-market growth product executive and changemaker. He works with mid-market product-driven software executives to solve their biggest growth problems. He scales product growth, optimizes ops and builds loyal customers. He has reduced customer churn 33%, and boosted sales 47% for clients. He makes a significant impact by building and launching world-changing AI-powered products. If you're looking for an engaging and inspiring speaker to spark creativity and innovation within your organization, set up an appointment to discuss your specific needs and identify a suitable topic to inspire your audience at your next corporate conference, symposium, executive summit, or planning retreat.
About PMI Silver Spring Chapter
We are a branch of the Project Management Institute. We offer a platform for project management professionals in Silver Spring, MD, and the DC/Baltimore metro area. Monthly meetings facilitate networking, knowledge sharing, and professional development. For event details, visit pmissc.org.
This comprehensive program covers essential aspects of performance marketing, growth strategies, and tactics, such as search engine optimization (SEO), pay-per-click (PPC) advertising, content marketing, social media marketing, and more
7. Example
Import java.io.*;
class Example {
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
8. public static void main(String args[])
All Java applications begin execution by calling main( ).
public keyword is an access modifier,which allows the
programmer to control the visibility of class members.
The keyword static allows main( ) to be called without
having to instantiate a particular instance of the class.
This is necessary since main( ) is called by the Java
Virtual Machine before any objects are made.
The keyword void simply tells the compiler that main( )
does not return a value.
9. public static void main(String args[])
Keep In mind that Java is case-sensitive.
Thus, Main is different from main.
String args[ ] declares a parameter named args which is an
array of instances of the class String. (Arrays are collections of
similar objects.)
Objects of type String store character
strings.
args receives any command-line arguments present when the
program is executed.
10. public static void main(String args[])
main( ) is simply a starting place for your program.
A complex program will have dozens of classes, only one of
which will need to have a main( ) method to get things
started.
In some cases, you won’t need main( ) at all. For example,
when creating applets (Java programs that are embedded in
web browsers)since the web browser uses a different means
of starting the execution of applets.
11. System.out.println()
System.out.println("This is a simple Java program.");
println( ) displays the string which is passed to it.
System is a predefined class that provides access to the system
out is the output stream that is connected to the console.
12. Data Types,
Java defines eight primitive types of data:byte,short,int,long,char,
float,double,and boolean.
The primitive types are also referred to as simple types.
These can be put in four groups
Integers : includes byte, short, int, and long, which are for
whole-valued signed numbers.
• Floating-point numbers :includes float and double, which
represent numbers with fractional precision.
• Characters : includes char, which represents symbols in a
character set, like letters and numbers.
• Boolean: which is a special type for representing true/false
values.
13. Integers
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values.
17. Characters
In Java, the data type used to store characters is char.
In C/C++, char is 8 bits wide.
In Java char is a 16-bit type.
The range of a char is 0 to 65,536.
There are no negative chars.
18. Booleans
Java has a primitive type, called boolean, for logical values.
have only one of two possible values, true or false.
This is the type returned by all relational operators, as in the
case of a < b.
boolean is also the type required by the conditional expressions
that govern the
control statements such as if and for.
19. Flow Control/Control Statements
Flow control describes the order in which the statements will be
executed at runtime.
A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a
program.
Java’s control statements can be :
Selection: allow program to choose different paths of execution
based upon the outcome of an expression or the state of a variable.
Iteration: . enable program execution to repeat one or more
statements (that is, iteration statements form loops).
Jump: Jump statements allow your program to execute in a
nonlinear fashion
20. Flow Control
Fflow Conrol
SSelection Statements IIterative Statements
Transfer
Statemets(Jump)
1.If else
2. switch
1. while
2. do while
3.for
4. for each
1. break
2. continue
3. Return
4. Label
5. Try catch
finaly
6. assert
21. Selection Statements
if else
conditional branch statement.
used to route program execution through two different
paths.
Syntax:
if (condition) //condition shold be a boolean value
{ statement1;} //sop(“hello”);
else
{statement2;}
22. Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block).
The condition is any expression that returns a boolean value.
The else clause is optional
Remember, only one statement can appear directly after the if or the else.
If you want to include more statements, you’ll need to create a block.
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else{
waitForMoreData();
}
23. 1.The argument to if statement should be boolean type.
If we are trying to provide any other type then we get compile
time error.
2. Else part and curly braces after if are optional.
Without curly braces{} only one statement is allowed under if,
which should not be declarative statements.
26. Nested ifs
A nested if is an if statement that is the target of another if or else.
if(i == 10)
{
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
27. The if-else-if Ladder
A common programming construct that is based upon a sequence of
nested ifs is the if-else if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
..
else
statement;
28. The if-else-if Ladder
Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; //April
String season;if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}}
29. switch
The switch statement is Java’s multiway branch statement.
It provides an easy way to dispatch execution to different
parts of your code based on the value of an expression
provides a better alternative than a large series of if-else-if
statements
30. General form of a switch statement
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
……
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
31. expression must be of type byte,short,int,char,an
enumeration, or String.
Each value specified in the case statements must be a
unique constant expression (such as a literal value).
Duplicate case values are not allowed.
The type of each value must be compatible with the
type of expression.
32. A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");break;
case 1:
System.out.println("i is one.");break;
case 2:
System.out.println("i is two.");break;
case 3:
System.out.println("i is three.");break;
default:
System.out.println("i is greater than 3.");}}}
33. In summary, there are three important features of the switch
statement to note:
•The switch differs from the if in that switch can only test for
equality, whereas if can evaluate any type of Boolean
expression.That is, the switch looks only for a match
between the value of the expression and one of its case
constants.
• No two case constants in the same switch can have identical
values.
•A switch statement is usually more efficient than a set of
nested ifs.
34. Iteration Statements
Java’s iteration statements are while, and do-while , for , for
each.
These statements create what we commonly call loops.
While
Its general form:
while(condition) {
// body of loop
}
36. do-while
Sometimes it is desirable to execute the body of a loop at least
once, even if the conditional expression is false to begin
with.
In other words, there are times when you would like to test
the termination expression at the end of the loop rather than
at the beginning.
The do-while loop always executes its body at least
once,because
40. for each/enhanced for loop
For-each is another array traversing technique like for loop, while loop,
do-while loop .
Iintroduced in Java5.
It starts with the keyword for like a normal for-loop.
Instead of declaring and initializing a loop counter variable, you declare
a variable that is the same type as the base type of the array, followed by
a colon, which is then followed by the array name.
In the loop body, you can use the loop variable you created rather than
using an indexed array element.
It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList)
41. Syntax:
for (type var : array)
{ statements using var; }
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
42. The drawback of the enhanced for loop is that it cannot
traverse the elements in reverse order.
Here, you do not have the option to skip any element
because it does not work on an index basis.
Moreover, you cannot traverse the odd or even elements
only.
But, it is recommended to use the Java for-each loop for
traversing the elements of array and collection because it
makes the code readable.
43. Advantages
It makes the code more readable.
It eliminates the possibility of programming errors.
45. Transfer (Jump )Statements
break statement
break statement is used inside loop or switch statement.
When compiler finds the break statement inside a loop,
compiler will abort the loop and continue to execute
statements followed by loop.
BreakDemo.java
46. continue statement:
continue statement is also used inside loop.
When compiler finds the continue statement inside a loop,
compiler will skip all the following statements in the loop and
resume the loop.
48. Lexical Issues
Java programs are a collection of whitespace, identifiers,
literals, comments, operators, separators, and keywords.
Whitespace
Java program could have been written all on one line or in
any other strange way you felt like typing it, as long as there
was at least one whitespace character between each token
that was not already delineated by an operator or separator.
In Java, whitespace is a space, tab, or newline.
49. Identifiers
Identifiers are used to name things, such as classes, variables,
and methods.
An identifiermay be any descriptive sequence of uppercase
and lowercase letters, numbers, or the underscore and
dollar-sign characters.
They must not begin with a number, lest they be confused
with a numeric literal.
Again, Java is case-sensitive, so VALUE is a different
identifier thanValue.
51. Literals
A constant value in Java is created by using a literal
representation of it.
52.
53. Comments
You have already seen two: single-line and multiline.
The third type is called a documentation comment.This type of
comment is used to produce an HTML file that documents
your program.
56. Array
Array is a collection of similar data type.
A single variable can hold only one value at a time,.
If we want a variable to store more than one value of same
type we use array.
Array is linear data structure.
It can store fixed number of values.
57. Arrays
An array is a group of like-typed variables that are referred to by a
common name.
Arrays of any type can be created and may have one or more
dimensions.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related
information.
58.
59. One-Dimensional Arrays
A one-dimensional array is,essentially,a list of like-typed variables.
The general form of a one-dimensional array declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array
The element type determines the data type of each element that
comprises the array.
Thus, the element type for the array determines what type of data
the array will hold.
For example, the following declares an array named month_days
with the type “array of int”:
int month_days[];
60. array-var = new type [size];
here new is a special operator that allocates memory.
month_days = new int[12];
62. class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
63. class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
64. Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally,
this matrix is implemented as an array of arrays of int.
65.
66. // Demonstrate a two-dimensional array.
classTwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++){
for(j=0; j<5; j++)
twoD[i][j] = k;
k++;}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}}}
67. This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
68. Ch 2:Classes, Interfaces and Packages
The class is at the core of Java.
Any concept you wish to implement in a Java program must
be encapsulated within a class.
Classes may contain only code or only data, most classes
contain both.
A class is declared by use of the class keyword.
69. General Form o Class
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
70. The data, or variables, defined within a class are called instance
variables., because each instance of the class (that is, each object of
the class) contains its own copy of these variables.Thus, the data
for one object is separate and unique from the data for another.
The code is contained within methods.
Collectively, the methods and variables defined within a class are
called members of the class.
In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.
Thus, as a general rule, it is the methods that determine how a
class’ data can be used.
71. A Simple Class
Here is a class called Box that defines three instance
variables: width, height, and depth.
Currently, Box does not contain any methods.
class Box {
double width;
double height;
double depth;
}
Box mybox = new Box(); // create a Box object called mybox
mybox.width = 100;
72. class Box {
double width;
double height;
double depth;}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10; mybox.height = 20; mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
} }
73. Declaring Objects
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
74.
75. Introducing Methods
This is the general form of a method:
type name(parameter-list) {
// body of method
}
Methods that have a return type other than void return a
value to the calling routine using the following form of the
return statement:
return value;
Here, value is the value returned.
78. Adding a Method That Takes
Parameters
Java program :BoxDemo5
79. Constructors
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is
syntactically similar to a method.
Once defined, the constructor is automatically called when the
object is created, before the new operator completes.
Constructors look a little strange because they have no return
type, not even void.
This is because the implicit return type of a class’ constructor is
the class type itself.
It is the constructor’s job to initialize the internal state of an object
so that the code creating an instance will have a fully initialized,
usable object immediately.
81. A constructor initializes an object immediately upon
creation.
Constructor have the same name as the class itself
A constructor is automatically called when an object is
created.
Syntax :
constructor_name([arguments])
{
body;
}
82. Rules to define Constructor
Constructor name must be same as its class name.
Constructor must have no explicitly return type not even
void.(the implicit return type of a class’ constructor is the
class type itself.)
Multiple constructor may exist in a class but all should have
different signature.
Constructors may be private ,protected or public.
public int add(int a, int b);
public int add(int a, int b,int c);
public double add(double a, double b);
85. Default Constructor:
If you don’t define a constructor ,then the compiler acreates a
default constructor.
Default constructor do not contain any parameters
Default constructors are created only if there are no constructors
defined by us.
A constructor that has no parameter is known as default
constructor.
In other words “when the object is created java creates a no-
argument constructor automatically known as default constructor”
Default constructor provides the default values to the
object(instance variables)like null to String and 0 to int.
BoxDemo6.java
86. Parameterized Constructors
A constructor that has parameters or arguments is known as
parameterized constructor.
Parameterized Constructor is used to provide different values to
the distinct objects.
Using parameterized constructor ,it is possible to initialize objects
with different set of values at the time of their creation. .
These different set of values initialized to objects must be passed
as arguments when constructor is invoked.
The parameter list can be specified in the parentheses in the same
way as parameter list is specified in the method.
Example BoxDemo7
92. class A
{
}
class B extends A
{
}
https://www.tutorialspoint.com/java/java_inheritance.htm
93. Types of Inheritance
Single inheritance.
Multi-level inheritance.
Multiple inheritance.
Hierarchical Inheritance.
Hybrid Inheritance.
94. Single Inheritance
Single inheritance is easy to understand.
When a class extends another one class only then we call it a
single inheritance.
The below flow diagram shows that class B extends only one
class which is A.
Here A is a parent class of B and B would be a child class of
A.
Program B.java
95. Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO
technology where one can inherit from a derived class,
thereby making this derived class the base class for the new
class.
As you can see in below flow diagram C is subclass or child
class of B and B is a child class of A.
example refer Z.java
96. Multiple Inheritance
Multiple Inheritance” refers to the concept of one class
extending (Or inherits) more than one base class.
The problem with “multiple inheritance” is that the derived
class will have to manage the dependency on two base
classes.
Most of the new OO languages like SmallTalk, Java, C# do
not support Multiple inheritance. Multiple Inheritance is
supported in C++
97. Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub
classes. In below example class B,C and D inherits the same
classA.A is parent class (or base class) of B,C & D. Read
More at – Hierarchical Inheritance in java with example
program.
JavaExample.java
98. Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a
combination of Single and Multiple inheritance.
A typical flow diagram would look like below.
A hybrid inheritance can be achieved in the java in a same
way as multiple inheritance can be!! Using interfaces. yes you
heard it right.
By using interfaces you can have multiple as well as hybrid
inheritance in Java.
100. A Superclass Variable Can Reference a
Subclass Object
A reference variable of a superclass can be assigned a
reference to any subclass derived from that superclass.
Example: Javaapp.java
101.
102. Member Access and Inheritance
Java’s access modifiers are
public
private
Protected: applies only when inheritance is involved
default
103. public :When a member of a class is modified by public,
then that member can be accessed by any other code.
private:When a member of a class is specified as private,
then that member can only be accessed by other members of
its class.
When no access modifier is used, then by default the
member of a class is public within its own package, but
cannot be accessed outside of its package, means default
Program :AccessTest .java
104. Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
105. Method Overloading
Method Overloading allows different methods to have the
same name, but different signatures where the signature can
differ by the number of input parameters or type of input
parameters or both.
Overloading is related to compile-time (or static)
polymorphism.
Example: MethodOverLoadDemo.java
106. Method Overriding
In a class hierarchy, when a method in a subclass has the same
name and type signature as a method in its super class, then
the method in the subclass is said to override the method in the
super class.
When an overridden method is called from within its
subclass, it will always refer to the version of that method
defined by the subclass.
The version of the method defined by the super class will be
hidden.
108. Dynamic Method Dispatch
Method overriding forms the basis for one of Java’s most
powerful concepts: dynamic method dispatch.
Dynamic method dispatch is the mechanism by which a call to
an overridden method is resolved at run time, rather than
compile time.
Dynamic method dispatch is important because this is how
Java implements run-time polymorphism.
An important principle: a superclass reference variable can
refer to a subclass object.
Java uses this fact to resolve calls to overridden methods at
run time.
109. When an overridden method is called through a superclass
reference, Java determines which version of that method to
execute based upon the type of the object being referred to
at the time the call occurs.Thus, this determination is made
at run time.
When different types of objects are referred to, different
versions of an overridden method will be called.
In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version
of an overridden method will be executed.
110.
111.
112. Static Fields and Static Methods
Static member variable
Static method : can access only static member variable , can
not access instance variables
Static inner class But we can not have Static variable in a
method
113. Understanding static
There will be times when you will want to define a class member that
will be used
independently of any object of that class.
Normally, a class member must be accessed only in conjunction with an
object of its class.
However, it is possible to create a member that can be used by itself,
without reference to a specific instance.
To create such a member, precede its declaration with the keyword
static.
When a member is declared static, it can be accessed before any objects
of its class are created, and without reference to any object.
You can declare both methods and variables to be static.
The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist.
114. Instance variables declared as static are, essentially, global
variables.
When objects of its class are declared, no copy of a static
variable is made.
Instead, all instances of the class share the same static
variable.
Methods declared as static have several restrictions:
•They can only directly call other static methods.
•They can only directly access static data.
•They cannot refer to this or super in any way
117. Introducing final
A field can be declared as final.
Doing so prevents its contents from being modified, making
it, essentially, a constant.
This means that you must initialize a final field when it is
declared.
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
118. Declaring a parameter final prevents it from being changed
within the method.
Declaring a local variable final prevents it from being
assigned a value more than once.
The keyword final can also be applied to methods, final
method cannot be overriden.
Final class can not be inherited.
120. Package
Package in java is a mechanism to encapsulate a group of
classes, sub packages and interfaces.
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.
121.
122.
123. Advantage of Java Package
1) Java package is used to categorize the classes and interfaces
so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
124. Ch. 3 :Generics
Generics means parameterized types.
The main purpose of generics is
1To provide type safety
2To resolve type casting
Generic concept is just like template in C++
135. Advantage of exception handling
Exception handling ensures that the flow of the program
doesn’t break when an exception occurs.
For example, if a program has bunch of statements and an
exception occurs mid way after executing certain statements
then the statements after the exception will not execute and
the program will terminate abruptly.
By handling we make sure that all the statements execute and
the flow of program doesn’t break
136. Difference between error &exception
Errors indicate that something severe enough has gone wrong, the
application should crash rather than try to handle the error.
Exceptions are events that occurs in the code.A programmer can
handle such conditions and take necessary corrective actions. Few
examples:
NullPointerException –When you try to use a reference that points to
null.
ArithmeticException –When bad data is provided by user, for example,
when you try to divide a number by zero this exception occurs because
dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException –When you try to access the
elements of an array out of its bounds, for example array size is 5 (which
means it has five elements) and you are trying to access the 10th
element.
137. Types of exceptions
1)Checked exceptions:
2)Unchecked exceptions:
1)Checked exceptions: All exceptions other than
Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the
programmer has handled them or not.
If these exceptions are not handled/declared in the program,
you will get compilation error. For example, SQLException,
IOException, ClassNotFoundException etc.
138. 2)Unchecked exceptions: Runtime Exceptions are also
known as Unchecked Exceptions.
These exceptions are not checked at compile-time so
compiler does not check whether the programmer has
handled them or not but it’s the responsibility of the
programmer to handle these exceptions and provide a safe
exit.
For example,ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
139. Try block
The try block contains set of statements where an exception
can occur.
A try block is always followed by a catch block, which
handles the exception that occurs in associated try block.
A try block must be followed by catch blocks or finally block
or both.
Syntax of try block
try{ //statements that may cause an exception }
While writing a program, if you think that certain statements
in a program can throw a exception, enclosed them in try
block and handle that exception
140. Catch block
A catch block is where you handle the exceptions, this block
must follow the try block.
A single try block can have several catch blocks associated
with it.
You can catch different exceptions in different catch blocks.
When an exception occurs in try block, the corresponding
catch block that handles that particular exception executes.
For example if an arithmetic exception occurs in try block
then the statements enclosed in catch block for arithmetic
exception executes.
141. Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
142. If an exception occurs in try block then the control of
execution is passed to the corresponding catch block.
A single try block can have multiple catch blocks associated
with it, you should place the catch blocks in such a way that
the generic exception handler catch block is at the last(see in
the example below).
The generic exception handler can handle all the exceptions
but you should place is at the end, if you place it at the before
all the catch blocks then it will display the generic message.
Superclass at the last.
146. Why we got this error?
This is because we placed the generic exception catch block
at the first place which means that none of the catch blocks
placed after this block is reachable.
You should always place this block at the end of all other
specific exception catch blocks.
147. Nested try catch
When a try catch block is present in another try block then it
is called the nested try catch block.
149. Finally block
A finally block contains all the crucial statements that must
be executed whether exception occurs or not.
The statements present in this block will always execute
regardless of whether exception occurs in try block or not
such as closing a connection, stream etc.
150. Syntax of Finally block
try
{
//Statements that may cause an exception
} catch { //Handling exception }
finally { //Statements to be executed }
152. The throw keyword
You can throw a user-defined exception or, a predefined
exception explicitly using the throw keyword.
There are two types of exceptions user-defined and
predefined each exception is represented by a class and which
inherits theThrowable class.
To throw an exception explicitly you need to instantiate the
class of it and throw its object using the throw keyword.
153. The throw keyword is used to create a custom error.
The throw statement is used together with an exception
type.
There are many exception types available in
Java:ArithmeticException, ClassNotFoundException, ArrayI
ndexOutOfBoundsException, SecurityException, etc.
154. public class Main {
static void checkAge(int age) {
if (age < 18) {
throw newArithmeticException("Access denied -You must be at least 18 years
old.");
}
else {
System.out.println("Access granted -You are old enough!");
}
}
public static void main(String[] args) {
checkAge(20); // Set age to 15 (which is below 18...)
}
}
155. Most programs cannot accomplish their goals without
accessing external data.
Data is retrieved from an input source.
The results of a program are sent to an output destination.
In Java, these sources or destinations are defined very
broadly.
For example, a network connection, memory buffer, or disk
file can be manipulated by the Java I/O classes.
Although physically different, these devices are all
handled by the same abstraction: the stream
156. An I/O stream, is alogical entity that either produces or
consumes information.
An I/O stream is linked to a physical device by the Java I/O
system.
All I/O streams behave in the same manner, even if the actual
physical devices they are linked to differ.
158. The java.io package also contains two deprecated
classes that are not shown in the preceding table:
LineNumberInputStream and
StringBufferInputStream.
These classes should not be used for new code.
159.
160. File
Although most of the classes defined by java.io ,operate
on streams, the File class does not.
It deals directly with files and the file system.
That is, the File class does not specify how information
is retrieved from or stored in files; it describes the properties
of a file itself.
A File object is used to obtain or manipulate the
information associated with a disk file
161. Files are a primary source and destination for data within
many programs.
Although there are severe restrictions on their use within
applets for security reasons, files are still a central resource
for storing persistent and shared information.
A directory in Java is treated simply as a File with one
additional property—a list of filenames that can be
examined by the list( ) method.
162. The following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath,String filename)
File(File dirObj,String filename)
File(URI uriObj)
Here,
directoryPath is the path name of the file;
filename is the name of the file or subdirectory;
dirObj is a File object that specifies a directory;
uriObj is a URI object that describes a file.
163. File f1 = new File("/");
File f2 = new File("/","autoexec.bat");
File f3 = new File(f1,"autoexec.bat");
164. Methods of File
File defines many methods that obtain the standard
properties of a File object.
getName( ) returns the name of the file;
getParent( ) returns the name of the parent directory;
exists( ) returns true if the file exists, false if it does
not.
167. Directories
A directory is a File that contains a list of other files and
directories.
When you create a File object that is a directory, the
isDirectory( ) method will return true.
In this case, you can call list( ) on that object to extract the
list of other files and directories inside.
170. Java I/O (Input and Output) is used to process the
input and produce the output.
Java uses the concept of a stream to make I/O operation fast.
The java.io package contains all the classes required for input
and output operations.
We can perform file handling in Java by Java I/O API.
In the above program, we used System's getProperty() method to get the user.dir property of the program.
171. Stream
A stream is a sequence of data. In Java, a stream is composed
of bytes. It's called a stream because it is like a stream of
water that continues to flow.
In Java, 3 streams are created for us automatically.All these
streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message
to the console.
172. System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
173. All Java programs automatically import the java.lang package.
This package defines a class called System, which encapsulates several
aspects of the run-time environment.
• For example, using some of its methods, you can obtain the current time
and the settings of various properties associated with the system
• .System also contains three predefined stream variables: in, out, and
err. These fields are declared as public, static, and final within System.
• This means that they can be used by any other part of your program and
without reference to a specific System object.
• System.out refers to the standard output stream. By default, this is the
console.
• System.in refers to standard input, which is the keyboard by default.
System.err refers to the standard error stream, which also is the console
by default. However, these streams may be redirected to any compatible
I/O device.
174. InputStream
Java application uses an input stream to read data from a
source in binary(byte)format;
It may be a file, an array, peripheral device or socket.
OutputStream
Java application uses an output stream to write data to a
destination in binary(byte)format;
it may be a file, an array, peripheral device or socket.
175.
176. OutputStream class
OutputStream class is an abstract class.
It is the superclass of all classes representing an output
stream of bytes.
An output stream accepts output bytes and sends them to
some sink.
Superclass of OutputStream is Object class.
177. Methods of OutputStream
Method Description
1) public void write(int)throws
IOException
is used to write a byte to the
current output stream.
2) public void write(byte[])throws
IOException
is used to write an array of byte to
the current output stream.
3) public void flush()throws
IOException
flushes the current output stream.
4) public void close()throws
IOException
is used to close the current output
stream.
178.
179. InputStream class
InputStream class is an abstract class.
It is the superclass of all classes representing an input stream
of bytes.
Super class of InputStream is Object.
180. Methods Of InputStream
Method Description
1) public abstract int read()throws
IOException
reads the next byte of data from the
input stream. It returns -1 at the
end of the file.
2) public int available()throws
IOException
returns an estimate of the number
of bytes that can be read from the
current input stream.
3) public void close()throws
IOException
is used to close the current input
stream.
181.
182. FileOutputStream Class
Java FileOutputStream is an output stream used for writing
data to a file.
If you have to write primitive values into a file, use
FileOutputStream class.
You can write byte-oriented as well as character-oriented
data through FileOutputStream class.
But, for character-oriented data, it is preferred to
use FileWriter than FileOutputStream.
184. FileOutputStream class methods
Method Description
protected void finalize() It is used to clean up the
connection with the file output
stream.
void write(byte[] ary) It is used to
write ary.length bytes from the
byte array to the file output
stream.
void write(byte[] ary, int off, int
len)
It is used to write len bytes from
the byte array starting at
offset off to the file output
stream.
void write(int b) It is used to write the specified
byte to the file output stream.
FileChannel getChannel() It is used to return the file
channel object associated with the
file output stream.
FileDescriptor getFD() It is used to return the file
descriptor associated with the
stream.
void close() It is used to closes the file output
stream.
186. FileInputStream Class
Java FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of raw
bytes) such as image data, audio, video etc.
You can also read character-stream data.
But, for reading streams of characters, it is recommended to
use FileReader class.
187. Declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream
188. FileInputStream class methods
Method Description
int available() It is used to return the estimated
number of bytes that can be read
from the input stream.
int read() It is used to read the byte of data
from the input stream.
int read(byte[] b) It is used to read up
to b.length bytes of data from the
input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of
data from the input stream.
long skip(long x) It is used to skip over and discards
x bytes of data from the input
stream.
FileChannel getChannel() It is used to return the unique
FileChannel object associated with
the file input stream.
FileDescriptor getFD() It is used to return
the FileDescriptor object.
protected void finalize() It is used to ensure that the close
method is call when there is no
more reference to the file input
stream.
void close() It is used to closes the stream.
190. FileWriter Class
FileWriter class is used to write character-oriented data to
a file.
It is character-oriented class which is used for file handling
in java.
Unlike FileOutputStream class, you don't need to convert
string into byte array because it provides method to write
string directly.
191. Declaration for Java.io.FileWriter class:
public class FileWriter extends OutputStreamWriter
192. Constructors of FileWriter class
FileWriter(String file) Creates a new file. It gets file name
in string.
FileWriter(File file) Creates a new file. It gets file name
in File object.
193. Methods of FileWriter class
Method Description
void write(String text) It is used to write the string into
FileWriter.
void write(char c) It is used to write the char into
FileWriter.
void write(char[] c) It is used to write char array into
FileWriter.
void flush() It is used to flushes the data of
FileWriter.
void close() It is used to close the FileWriter.
195. FileReader Class
Java FileReader class is used to read data from the file.
It returns data in byte format like FileInputStream class.
It is character-oriented class which is used for file handling
in java.
196. Java FileReader class declaration
public class FileReader extends InputStreamReader
197. Constructors of FileReader class
Constructor Description
FileReader(String file) It gets filename in string. It opens
the given file in read mode. If file
doesn't exist, it throws
FileNotFoundException.
FileReader(File file) It gets filename in file instance. It
opens the given file in read mode. If
file doesn't exist, it throws
FileNotFoundException.
198. Methods of FileReader class
Method Description
int read() It is used to return a character in
ASCII form. It returns -1 at the end
of file.
void close() It is used to close the FileReader
class.
200. Lambda Expressions
Nested Classes and Inner Classes
Anonymous Inner Classes
Default Methods and Functional Interfaces
Introduction to Lambda Expressions
Passing Lambda Expressions as Arguments
Predefined Functional Interfaces
201. Nested and Inner Classes
It is possible to define a class within another class; such classes are
known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing
class.
Thus, if class B is defined within classA, then B does not exist
independently of A.
A nested class has access to the members, including private
members, of the class in which it is nested.
However, the enclosing class does not have access to the members
of the nested class.
A nested class that is declared directly within its enclosing class
scope is a member of its enclosing class.
It is also possible to declare a nested class that is local to a block.
202. There are two types of nested classes: static and non-static.
A static nested class is one that has the static modifier applied.
Because it is static, it must access the non-static members
of its enclosing class through an object.
That is, it cannot refer to non-static members of its enclosing class
directly.
Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class.
An inner class is a non-static nested class.
It has access to all of the variables and methods of its outer class
and may refer to them directly in the same way that other non-
static members of the outer class do
203. Inner class
Sometimes we declare one class in another class these class is
called as inner class
The most important type of nested class inner class.
An inner class is a non-static nested class.
It has access to all of the variables and methods of its outer
class and may refer to them directly in the same way that
other non-static members of the outer class do.
205. class Outer
{
class inner
{
public static void main(String args[])
}
}//Save as Outer.java
It gives error Because inner class does not have static
declaration.
206. class Outer
{
class inner
{
public void m1()
{
System.out.println(“Inside inner method”)
}
}
public static void main(String args[])
{
}
}
207. Without existing Outer Object Inner object does not exist.
1)Outer o=new Outer();
Outer.Inner i=o.new Inner();
2)Outer.Inner i= new Outer ().new Inner();
208. Accessing Inner class from static area of outer class.
Outer.java
Accessing Inner class from Instance area of outer class.
OuterCase2.java
Accessing Inner class from outside of outer class.
OuterCase3.java
209. In Inner class we cannot declare static members but we can
access static or non static members.
Modifiers used for
Outer class: public,default,abstract,strictfp, final
Inner class: public, default,abstract,
strictfp,final,private, protected,static
210. Nesting of Inner class
Inside a inner class we can declare another inner class .That is
nesting of inner classes is possible.
TestIM.java
211. Anonymous Inner class
Sometimes Inner class without name called Anonymous Inner
Popcorn p=new Popcorn()
{
};
212. Whenever permanent requirement is there better to go for
top level class and whenever one time requirement then go
to anonymous inner class.
213. Popcorn p=new Popcorn();
We are creating Popcorn object
Popcorn p=new Popcorn()
{
};
1) We are declaring a class that extends Popcorn class without
name (Anonymous Inner class)
2) For that child class we are creating an object with a parent
reference.
214. Popcorn p=new Popcorn()
{
Public void teste()
{
System.out.println(“spicy”);
}};
1) We are declaring a class that extends Popcorn class without
name (Anonymous Inner class)
2) For that child class we are creating an object with a parent
reference
3) In the child class we are overriding teste() method.
216. Static nested class
Sometimes we can declare inner class with a static modifier,
such type of inner classes are called static inner classe.
In the case of normal or regular inner class without existing
outer class object there is no chance of existing inner class
object .
That is inner class object is strongly associated with outer
class object.
But in the case of static nested classes without outer class
object there may be chance of existing nested class object.
Hence static nested class object is not strongly associated
with the outer class object.
218. If you want to create nested class object outside of outer class
then we can create as following
Outer.Nested n=new Outer.Nested()
Normal Inner class does not have static declaration ,but static
nested class have.
220. Normal /regular inner class static nested class
strongly associated with strongly associated with
outer obj
cannot declare static data member can declare static data
member
main() can not declare main() can
declare
access static as well non static data member access only
static data member
221. Lamda Expression
Java 8 new Features (came in 2014)
Lamda Expressions
Functional Interfaces
Default method
Predefined Functional
Interfaces:Predicates,Functions,supplier,consumer
Double colon operator(Constructor and method references)
Stream API
Date andTime (JodaTime API)
Nashorn java Script
222. Lamda Expressions
1930 Lambda calculus was introduced in mathematics.
Because of lambda calculus benefit programming languages
are making use of LC concept.
First programming language which uses Lambda expressions
is LISP.
C,C++,C#,Python,Ruby,Javascript,Java. Uses LE
223. Java is Object Oriented Language.
There are several benefits with functional programming
language.
So to enable functional programming concepts Lambda
expressions are came into picture.
224. What is Lambda Expression?
1)Anonymous function/nameless function
2) not having name, no return type,no modifier
Lambda Expression called as closures
225. Examples
Normal method to print hello
public void m1()
{
System.out.println(“Hello”);
}
Converted into Lambda Expression
() ->System.out.println(“Hello”);
226. public void add(int a, int b)
{
System.out.println(a+b)
}
(int a, int b)->System.out.println(a+b);
Some times based on context (situation)compiler going to
guess types automatically .
(a, b)->System.out.println(a+b);
228. Big advantage of LE is conciseness
If body contains more than one line then { } are required
If passing only one argument then no need of ()
If only one statement then no need of {}
229. Conclusions
1.LA may have any number of arguments : zero ,one,two…
2)For one argument LE parenthesis are optional
3)for (a,b)->sop(a+b) parenthesis are compulsary 2
arguments are here
4)(a,b)->{ sop(a+b)
sop(a-b)
sop(a*b)
}
{} are required because more then one statements are here
230. How to Call/Invoke Lambda Expression
To call LE special concept is required that is functional
Interface.
Wherever there is FI then only we use LE
231. Functional Interface
Normal Interface
Runnable
Callable
Comparable
Serializable
RandomAccess
Clonable
SingleThreadModel
Does not contain any method so calles Maker Interfaces
232. Marker Interfaces
Serializable
RandomAccess
Clonable
SingleThreadModel
If by implementing these intefaces our object get some extra
ability such type of interfaces are called Marker Interfaces.
233. Runnable=run()
Callable=call()
Comparable=compareTo()
Interfaces contains only abstract methods.
Above interfaces contains only single abstract method.
SAM=Single Abstract Method.
Interfaces which contains single abstract method are called as
Functional Interfaces
There are so many FI are present.
234. From java 1.8 version onwards contains default and static methods
But prior to 1.8 version, only abstract methods.
default void m1(){} and static void m1(){} such concepts are
arrived in 1.8 version.
Means From java 1.8 version onwards contains abstract, default
and static methods .
For Functional Interface restriction on only abstract method i.e
only one abstract method ,no restriction on default and static
method .
Means FI should have only one AM and any number of DM and
SM
237. Lambda expression concept is used when only with FI .
Means without FI we can not use LE.
TestLE3
LETestLE3.java
LETestLE4.java LE with static method :static and default
method also included
LETestLE5.java calculate square of number
LETestLE6.java
238. Include FP in java
Code readable maintainable concise,clean code
Parallel programming
To use API very easily and effectively.
239. Collections Framework and Stream API
Implementing equals, hashcode and toString methods
The Comparable interface and Comparator interface
The Collection interface, List interface, Map interface
Using Lists:ArrayList and LinkedList classes
Using Maps: HashMap andTreeMap classes
StreamAPI
Retrieving a Stream from a Collection
Filtering Streams using filter method
Mapping Streams using map method
Collecting Streams into Collections using collect method
Reducing Streams to values using reduce method
Using forEach method
240. Overview of Collection
Need of collection:
int x=10; x is integer variable which store one integer value.
For storing 1000 integer values we have to declare 1000 int variable.
Then program code will more than 1000 lines it is difficult to remember
which variable storesn which value.
Readability is difficult.
Then option is to storeArray of size 1000 of datatype int.
Readability may be achieved
But Some of disadvantages:
1)Arrays are Fixed in size.To useArray you should know size in advance.
2)Array can store only homogeneous data.In int type of array you can store
only int data not of other type.
241. Student s=new Student ();
Can store only only Student datatype.
But Object o=new Object();
can store different datatype objects.
3)Arrays are not implemented under standard database.No
readymate method support for arrays ,which increases
complexity of program.
TO overcome
242. An array is an indexed collection of fixed number of
homogeneous data elements.
The main advantage of arrays is we can represent multiple
values by using single variable so that readability od code will
be improved.
243. Limitations of Arrays
Arrays are fixed in size.That once we creates an array,there is
no chance of increasing or decreasing the size based on our
requirement. Due to this ,to use Array concepts compulsary
we should know size in advance which may not possible
always
Array can hold only homogeneous datatype elements .
example Student s[]=new Student[10000]
s[0]=new Student(); valid
s[1]=new Customer(); invalid ,incompatible type
Found Customer
Required Student
244. We can solve this problem by using Object typeArrays.
Object a[]=new Object[10000];
a[0]=new Student();
a[1]=new Customer();
3)Arrays concept is not implemented based on some standard
data structure and hence readymade method support is not
available.
For every requirement we have to write a code explicitly,
which increases complexity of programming.
245.
246.
247. Collections:
To overcome above problems of Arrays we should go for
Collections concept.
1)Collections are growable in nature that is based on our
requirement we can increase or decrease the size.
2)Collections can hold both homogeneous and heterogeneous
objects
3)Every collection class is implemented based on some
standard data structure hence for evry requirement readymade
method support is available.
Being a programmer we are responsible to use those methods
and we are not responsible to implement those methods
248. Differences between Arrays and
Collections
Array Collection
1 Arrays are fixed in size. That is once we
create an array we cannot increase or
decrease the size based on our
requirement.
Collections are growable in nature.tht is based on our
requirement we can increase or decrease size.
2 With respect to memory arrays are not
recommended to use
With respect to memory Collections are not
recommended to use
3 With respect to performance arrays are
recommended to use
With respect to performance Collections not are
recommended to use
4 Array can hold only homogenous
dataype elements
Collections can hold both homogenous
heterogeneous dataype elements
There is no underline Data Structure for
Arrays and hence readymate method
support is not available, for every
requirement we have to write code
explicitly which increases complexity of
programming.
Every Collection class is implemented based on some
DS and hence for every requirement readymate
method support is available, being a programmer we
can use these methods directly and we are not
responsible to implement those methods.
Arrays can hold both primitives and
objects
Collections can hold only object types but not
primitives
249. Collection
Collection: If you want to represent a group of individual
objects as a single entity then we go for Collection.
Collection Framework :It contains several classes and
interfaces which can be used to represent a group of
individual objects as single entity.
In java collection framework is equivalent to STL(Standard
template Library)
252. 1.Collection(I)
If we want to represent a group of individual object as a
single entity then we should go for Collection
Collection Interface defines the most common methods
which are applicable for any collection object.
In general Collection Interface is considered as root Interface
of Collection Framework.
There is no concrete class which implements Collection
Interface directly.
253. Difference between Collection and Collections
Collection is an Interface . If we want to represent a group of
individual object as a single entity then we should go for
Collection.
Collections is an utility class present in java.util package to
define several utility methods for Collection objects(like
sorting , searching etc)
254. 2.List(I)
It is the child interface of Collection.
If we want to represent the group of individual objects as
single entity where duplicates are allowed and insertion
order must be preserved then we should go for List.
255. In 1.2 versionVector and Stack classes are reengineered or
modified to implement List interface
256. 3.Set(I)
It is the child interface of Collection.
If we want to represent the group of individual objects as
single entity where duplicates are not allowed and insertion
order not required then we should go for Set.
257. 4.SortedSet(I)
It is the child interface of Collection.
If we want to represent the group of individual objects as
single entity where duplicates are not allowed and all objects
should be inserted according to some sorting order then we
should go for SortedSet.
258. 5.NavigableSet(I)
It is the child interface of SortedSet.
It contains several methods for navigation purposes.
259. Differences Between List and Set
Differences Between List and Set
List Set
1 Duplicatesareallowed Duplicatesarenotallowed
2 Insertionorderpreserved Insertionordernotpreserved
260. 6.Queue(I)
It is the child interface of Collection.
If we want to represent the group of individual objects prior
to processing then we should go for Queue.
Usually Queue follows First In Forst Out order but based on
our requirement we can implement our own priority order
also
Example:Before sending a mail all mail ids we have to store
in some data structure .In which order we added mail ids I
the same order only mail should be delivered .For this
requirement Queue is best choice.
262. All the above Interfaces (Collection, List, Set ,SortedSet,
NavigableSet and Queue)meant for representing a group of
individual objects.
If we to represent a group of objects key value pairs then we
should go for Map.
263. Map(I)
Map is not child interface of Collection.
If you want to represent a group of objects as key value pairs
then we should go for map.
Both key and value are objects only.
Duplicates keys are not allowed but values can be duplicated.
Sr.No(Key) Name (Value)
101 Aa
102 Bb
103 Cc
265. 8.SortedMap
It is the child interface of Map.
If we want to represent a group of key value pairs according
to some sorting order of keys then we should go for
SortedMap
In SortedMap the sorting should be based on key but not
based on value.
266. 9.NavigableMap(I)
It is the child interface of SortedMap.
It defines several methods for navigation purposes.
267. The following are legacy characters present in Collection
Framework
Enumeration(I)
Dictionary(AC)
Vector(C)
Stack(C)
Hashtable(C)
Properties(C)
268. Collection Interface
If we want to represent agroup of individual object as asingle
entity then we should go for Collection.
Collection Interface defines the most common methods
which are applicable for any collection object.
In general Collection Interface is considered as root Interface
of Collection Framework.
There is no concrete class which implements Collection
Interface directly.
269. Methods of Collection Interface
boolean add(Object o)
boolean addAll(Collection c)
boolean remove(Object o)
boolean removeAll(Collection c)
boolean retainAll(Collection c):Remove all objects except those present in
c.
void clear()
boolean contains(Object o)
boolean containsAll(Collection c)
boolean isEmpty()
int size()
Object[] toArray()
Iterator iterator()
270. There is no concrete class which implements Collection
Interface directly.
271. List Interface
It is the child interface of Collection.
If we want to represent the group of individual objects as
single entity where duplicates are allowed and insertion
order must be preserved then we should go for List.
We can preserve insertion order via index and we can
differentiate duplicate objects by using index.
Hence index will play very important roll in List.
272. Methods of List
List interface defines the following specific methods
void add(int index,Object o)
void addAll(int index,Collection c)
Object get(int index)
Object remove(int index)
Object set(int index Onject new) : to replace the element present
at specified indx with provided Object and returns old object.
int indexOf(Object o) :returns index of first occurrence of o
int latIndexOf(Object o)
ListIterator listIterator()
273. ArrayList class
The underlined data structure is resizable array or growable
array
Duplicates are allowed
Insertion order is preserved.
Heterogeneous objects are allowed(ExceptTreeSet and
TreeMap heterogeneous objects are allowed).
Null insertion is possible.
274. Constructors of ArrayList
1)ArrayList l=new ArrayList();
Creates an empty ArrayList object with default initial capacity
of 10
Once ArrayList reaches its max capacity then a new AL object
will be created with
new capacity = current capacity*(3/2)+1
2)ArrayList l=new ArrayList(int initialcapacity)
Creates an empty AL object with specified initial capacity
3)ArrayList l=new ArrayList(Collection c)
Creates an equivalent AL object for the given collection .
276. Usually we can use Collections to hold and transfer objects from
one location to another location(Container).
To provide support for this requirement every Collection class by
default implements Serializable and Clonable interfaces.
ArrayList andVector classes implements RandomAccess interface
so that any random elements we can access with same speed.
RandomAccess Interface present in java.util package and it doesn’t
contain any method hence it is marker interface, where required
ability will be provided automatically by the JVM
278. ArrayList is best choice if ever frequent operation is retrieval
operation(Because AL implements RandomAccess interface).
Al is worst choice if ever frequent operation is insertion or
deletion at the middle.
279. Difference between ArraylList and
Vector
ArrayList Vector
1 Every method present in the AL is non
synchronised
Every method present in the Vector is synchronised
2 At a time multiple threads are allowed
to operate on AL objects and hence it is
not Thread Safe
At a time only one threads is allowed to operate on
Vector objects and hence it is Thread Safe
3 Relatively performance is high because
threads are not required to wait to
operate on AL object
Relatively performance is low because threads are
required to wait to operate on Vector object
4 Introduced in 1.2 version and it is non
legacy
Introduced in 1.0 version and it is legacy
280. How to get Synchronised version of ArrayList object?
Bydefault AL is nonsynchronised but we can get synchronised
version of AL object by using synchronisedList () method of
Collections class.
Public static List synchronizedList(List l)
ArrayList l=new ArrayLIst();
List ll=Collection.synchronizedList(l);
Where,l is nonsynchronised and ll is synchronized.
281. Similarly we can get synchronized version of Set and Map
objects by using the following methods of Collections class
Public static Set synchronizedSet(Set t)
Public static Map synchronizedMap(Map m)
282. LinkedList :
The underlined datastructure is doubly linked list .
Insertion order is preserved
Duplicate objects are allowed
Heterogeous objects are allowed.
Null insertion is possible
LL implements Seializable and Clonable interfaces but not
RandomAccess
LL is best choice if our frequent operation insertion or
deletion in the middle.
LL is worst choice if our frequent operation is retrieval
operation.
283. LinkedList Constructor
LinkedList l=new LinkedList(); creates an empty LL object
LinkedList l=new LinkedList(Collection c); Creates an
equivant object for the given Collection
284. LL class Specific methods
Usually we can use LL to develop stacks and queues.
To provide support for this requirement LL class defines
following specific methods
void addFirst(Object o)
void addLast(Object o)
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();
286. Differences between AL and LL
ArrayList LinkedList
1 AL is best choice if our frequent
operation is retrieval.
LL is best choice if our frequent operation is
insertion or deletion in the middle.
2 AL is worst choice if our frequent
operation is insertion or deletion in
the middle because internally several
shift operations are performed.
LL is worst choice if our frequent operation is
retrieval.
3 Elements are stored in consecutive
memory location and hence retrieval
operation become easy.
Elements are not stored in consecutive memory
location and hence retrieval operation become
complex/difficult.
287. Vector
The underlined DS is resizable array or growable array
Insertion order is preserved
Duplicates are allowed.
Heterogeneous objects are allowed.
Null insertion is possible.
It implements Serializable, Clonable and RandomAccess
interfaces.
Evey method present in theVector is synchronised and hence
Vector object isThreadSafe.
288. Constructors of Vector
1)Vector v=newVector();
Creates emptyVector of size 10,when vector reaches its max
capacity then a newVector object will be created with the
New capacity=current capacity*2;
2)Vector v=newVector(int initial capacity);
Creates emptyVector object with specified initial capacity.
3)Vector v=newVector(int initial capacity, int incremental
capacity);
290. Object class
It is in java.lang package
The most commonly required methods for every java
class(whether it is predefined class or customized class)are
defined in a separate class which is nothing but Object class
Every class in java is child class of Object either directly or
indirectly so that Object class methods by default available to
every java class.
Hence Object class is considered as root of all java classes.
291. If our class doesn’t extend any other class then only our class
is the direct child class of Object.
• class A
• {
• }
Object
A
292. If our class extends any other class then our class is indirect
child class of Object
• class B extendsA
• {
• }
• This is called as Multilevel Inheritance
Object
A
B
294. Methods of Object class
1.public String toString()
2.public native int hashCode()
3.public boolean equals(Object o)
4.protected native objectClone()throws
CloneNotSupportedException
5.protected void finalize()throwsThrowable
6.public final Class getClass()
7.public final void wait()throws InteruptedException
8.public final native void wait(long ms)throws InteruptedException
9.public final void wait(long ms, int ns)throws InteruptedException
10.public native final void notify()
11.public native final void notifyAll()
295. toString()
We can use toString()to get string representation of an
object.
String s=obj.toString()
Whenever we are trying to print object reference internally
toString() will be called.
Student s= new Student();
System.out.println(s);
System.out.println(s.toString());
296. If our class doesn’t contain toString () then Object class toString()
will executed.
Example :Student.java
In this example Object class toString() got executed whikch is
implemented as follows
public String toString()
{
return getClass().getName()+@+Integer.toHexString(hasCode);
}
Classname@hashCode_in_hexadecimal_form.
298. hashCode()
For every object a unique number generated by JVM which is
nothing but hashcode.
Hashcode won’t represent address of object.
JVM will use hashcode while saving objects into hashing related
datastructures like hashtable,hashMap,hashSet etc.
The main advantage of saving objects based on hashcode is
search operation will become easy(The most powerful search
algorith upto today is Hashing.)
If you are giving chance to Object class to use hashcode() it will
generates hashcode based on address of objects.
It doesn’t mean hascode represent address of the object
Based on our requirement we can override hashcode () in our class
to generate our own hashcode.
299. public native int hashCode()
Overriding hashCode() is said to be proper if for every object
we have to generate a unique number as hashcode.
301. equals()
We can use equals() to check equality of two objects.
Example obj1.equals(obj2).
If our class doesn’t contain equals() then Object class equals()
will be executed.
303. In the above example Object class equals() got executed
which is meant for reference comparison (Address
comparison)that is if two references pointing to same objects
then only equals() return true.
Based on our requirement we can override equals() method
for content comparison
304. Comparable Interface
Present in java.lang package .
It contains only one method compareTo()
public int compareTo(Object obj)
So return type of compareTo() is int.
1. obj1. compareTo(obj2) returns positive;
if obj1 comes after obj2;
2. obj1. compareTo(obj2) returns negative;
if obj1 comes before obj2;
3. obj1. compareTo(obj2) returns 0;
if obj1 and obj2 are equal;
305. An object is said to be comparable if and only if
corresponding class implements Comparable interface.
String class , and allWrapper classes already implement
Comparable interface but StringBuffer class doesn’t
implement Comparable interface .
307. Comparator Interface
Present in java.util package
Define two methods
compare() and equals()
1.public int compare(Object obj1,Object obj2);
returns positive; if obj1 comes after obj2;
returns negative; if obj1 comes before obj2;
returns 0; if obj1 and obj2 are equal;
2. public boolean equals(Object obj)
308. Whenever we are implementing Comparator interface
compulsory we should provide implementation for
compare () and we are not require to provide
implementation for equals() because it is already available to
our class from Object class throw inheritance.
310. Map Interface
Map is not child interface of Collection Interface.
If we want to represent a group of objects as key value pairs
Then we should go for Map.
Both keys and values are Objects only
Duplicate keys are not allowed, but values can be duplicated
Each key value pair is called Entry.
Hence Map is considered as a collection of entry objects
313. Map Interface Methods
1.Object put(Object key, Object value)
To add one key value pair to the Map. If the key is already
present the old value will be replaced with new value and
returns old value
Example m.put(101,”aa”) return null;
m.put(102,”bb”) returs null;
m.put(101,”cc”) returns aa;
314. Map Interface Methods
2.void putAll(Map m) A group key value pair will be added.
3.Void putAll(Map m)
4.Object get(Object key)returns the value associated with specified
key.
5.Object remove (Object key):removes the entry associated with
specified key.
6.boolean containsKey(Object key)
7.boolean containsValue(Object value)
8.boolean isEmpty()
9.int size();
10.void clear();
315. Map Interface Methods(Collection
views of Map)
11. Set getKey() we get Set of only keys.
12. Collection getValue() we get only values .Duplicates
possible,orders are not important.
13. Set entrySet() we get Set of entry objects.
By applying these methods we get collection related
terminology.
316. Entry Interface
Map is a group of key value and each key value pair is called as
Entry .So Map is considered as collection Entry objects
Without existing Map there is No chance of existing Entry object
So Entry interface is defined inside Map Interface
Interface Map
{
Interface Entry
{
}
}
317. Entry specific methods
Object getKey()
Object getValue()
Object setValue(Object value)
Above methods can apply only on Entry objects
318. HashMap class
It implements Map interface
This is Hashtable
Insertion order is not preserved and it based on hashcode of keys.
Duplicate keys are not allowed but values can be duplicated.
Heterogeneous objects are allowed for key and value.
Null is allowed for keys(only once).
Null is allowed for values(any number of times).
HashMap implements Serializable and Clonable interfaces but not
RandomAccess.
HashMap is best choice if our frequent operation is serach
operation .
319. HashMap class constructors
1.HashMap m=new HashMap () :creates an empty hash map
object with default intial capacity 16 and default filld ratio
0.75.
2.HashMap m=new HashMap (int initialcapacity).
creates an empty hash map object with specified intial capacity
and default field ratio 0.75.
3. HashMap m=new HashMap (int initialcapacity, float
filldratio).
4. HashMap m=new HashMap (Map mm) .you may get
equivalent HashMap mby providing Map mm
321. HashMap
Methods of HshMap are not Synchronized
Multiple threads can operate at a same time so no thread
safe.
Threads have to wait,so performance is high.
Null values are allowed.
Not legacy introduced in 1.0.
322. Stream API
The Java Stream API provides a more functional
programming approach to iterating and processing elements
of e.g. a collection.The Java Stream API was added to Java in
Java 8.
The Java Stream API is not related to the Java InputStream
and Java OutputStream of Java IO.
The InputStream and OutputStream are related to streams of
bytes.
The Java Stream API is for processing streams of objects - not
bytes.
323. Java Stream Definition
A Java Stream is a component that is capable of internal
iteration of its elements, meaning it can iterate its elements
itself.
325. Stream.filter()
The Java Stream filter() can be used to filter out elements
from a Java Stream.
The filter method takes a Predicate which is called for each
element in the stream.
If the element is to be included in the resulting Stream,
the Predicate should return true.
If the element should not be included, the Predicate should
return false.
Stream<String> longStringsStream = stream.filter((value) -
> { return value.length() >= 3; });
327. map()
he Java Stream map() method converts (maps) an element to
another object.
For instance, if you had a list of strings it could convert each
string to lowercase, uppercase, or to a substring of the
original string, or something completely else.
Here is a Java Stream map() example:
List<String> list = new ArrayList<String>();
Stream<String> stream = list.stream();
Stream<String> streamMapped = stream.map((value) ->
value.toUpperCase());
328. 0, 10, 15, 6, 4]
[0]
[0, 20, 30, 12, 8]
this is output of StreamDemo1