0% found this document useful (0 votes)
25 views

Java Notes for MTE - 3 Units

Uploaded by

ayushpathak7777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Java Notes for MTE - 3 Units

Uploaded by

ayushpathak7777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 339

Java Programming

E1UA307C(PP)
Introduction to Java & Its features

Sun Microsystems Project ‘Green’ 1991 – OAK – 1995 Java


Java Programming
What is Java?
➢ Java is a popular programming language, created in 1995. It is owned by
Oracle, and more than 3 billion devices run Java.
➢ It is used for:
• Mobile applications (especially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!
Java Programming
Why Use Java?
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
• It is one of the most popular programming languages in the world.
• It is easy to learn and simple to use.
• It is open-source and free.
• It is secure, fast and powerful.
• It has a huge community support (tens of millions of developers).
• Java is an object-oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs.
• As Java is close to C++ and C#, it makes it easy for programmers to switch
to Java or vice versa.
Java Programming
➢ Features of Java:
• Simple
• Object-Oriented Programming Language
• Platform Independent
• Robust
• Secure
• Distributed
• Multithreading
• Portable
• High Performance
• Dynamic
Java Programming
➢ Simple:
• Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, and Explicit memory
allocation.

➢ Object-Oriented Programming Language:


• Organizing the program in the terms of collection of objects is a way of object-
oriented programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Java Programming
➢ Platform Independent:
• Compiler converts source code to bytecode and then the JVM executes the
bytecode generated by the compiler.
• This bytecode can run on any platform be it Windows, Linux, or macOS.
• Each operating system has a different JVM, but the output produced by all the
OS is the same after the execution of bytecode.
• That is why we call java a platform-independent language.
Java Programming
➢ Platform Independent:
• Compiler converts source code to bytecode and then the JVM executes the
bytecode generated by the compiler.
• This bytecode can run on any platform be it Windows, Linux, or macOS.
• Each operating system has a different JVM, but the output produced by all the
OS is the same after the execution of bytecode.
• That is why we call java a platform-independent language.
➢ Robust:
• Java language is robust which means reliable.
• It is developed in such a way that it puts a lot of effort into checking
errors as early as possible.
• The main features of java that make it robust are garbage collection,
Exception Handling, and memory allocation.
Java Programming
➢ Secure:
• In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so.
• Several security flaws like stack corruption or buffer overflow are impossible to
exploit in Java.
• Also java programs run in an environment that is independent of the
os(operating system) environment which makes java programs more
secure.
➢ Distributed:
• We can create distributed applications using the java programming language.
• The java programs can be easily distributed on one or more systems that
are connected to each other through an internet connection.
Java Programming
➢ Multithreading:
• Java supports multithreading.
• It is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of the CPU.

➢ Portable:
• As we know, java code written on one machine can be run on another
machine.
• The platform-independent feature of java in which its platform-independent
bytecode can be taken to any platform for execution makes java portable.

➢ High Performance:
• Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler.
Java Programming

➢ Dynamic:
• Java being completely object-oriented gives us the flexibility to add classes,
new methods to existing classes and even create new classes through sub-
classes.
• Java even supports functions written in other languages such as C, C++ which are
referred to as native methods.
Features of Object-Oriented Programming
Object-Oriented Programming:
➢ Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
➢ It simplifies software development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
➢ Object:
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
Java Programming
• An Object can be defined as an instance of a class.
• An object contains an address and takes up some space in memory.
• Objects can communicate without knowing the details of each other's data or code.
• The only necessary thing is the type of message accepted and the type of response
returned by the objects.
Example:
• A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
➢ Class:
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Java Programming
➢ Inheritance:
• When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance.
• It provides code reusability.
• It is used to achieve runtime polymorphism.
➢ Polymorphism:
• If one task is performed in different ways, it is known as
polymorphism.
• For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Another example can be to speak something;
• For example, a cat speaks meow, dog barks woof, etc.
Java Programming
➢ Abstraction:
• Hiding internal details and showing functionality is known as abstraction.
• For example: phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
➢ Encapsulation:
• Binding (or wrapping) code and data together into a single unit are
known as encapsulation.
• For example: a capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation.
• Java bean is the fully encapsulated class because all the data members are
private here.
A typical structure of a Java program contains the following elements:

1. Documentation Section
2. Package Declaration
3. Import Statements
4. Interface Section
5. Class Definition
6. Class Variables and Variables
7. Main Method Class
8. Methods and Behaviors
1. Documentation Section

o The documentation section is important but optional for a Java program.


o It includes basic information about a Java program.

o The information includes the author's name, date of creation, version, program name, company
name, and description of the program. It improves the readability of the program.

o Whatever we write in the documentation section, the Java compiler ignores the statements during the
execution of the program.

o To write the statements in the documentation section, we use comments.


o The comments may be single-line, multi-line, and documentation comments.
o Single-line Comment: It starts with a pair of forward slashes (//).
o For example:
//First Java Program

o Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
o For example:
/*It is an example of
multiline comment*/

o Documentation Comment: It starts with the delimiter (/**) and ends with */.
o For example:
/**It is an example of a documentation comment*/
Package Declaration

o The package declaration is optional.


o It is placed just after the documentation section.
o we declare the package name in which the class is placed.
o Note that there can be only one package statement in a Java program.
o It must be defined before any class and interface declaration.
o It is necessary because a Java class can be placed in different packages and directories based on the
module they are used.
o For all these classes package belongs to a single parent directory. We use the keyword package to
declare the package name.

o For example:
1. package javatpoint; //where javatpoint is the package name
2. package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory
Import Statements
o The package contains many predefined classes and interfaces.
o If we want to use any class of a particular package, we need to import that class.
o The import statement represents the class stored in the other package.
o We use the import keyword to import the class. It is written before the class declaration and after the
package statement.
o We use the import statement in two ways, either import a specific class or import all classes of a
particular package.
o In a Java program, we can use multiple import statements.

o For example:
1. import java.util.Scanner; //it imports the Scanner class only
2. import java.util.*; //it imports all the class of the java.util package
Interface Section
o It is an optional section. We can create an interface in this section if required.
o We use the interface keyword to create an interface.
o An interface is slightly different from the class. It contains only constants and method declarations.
o Another difference is that it cannot be instantiated.
o We can use interface in classes by using the implements keyword.
o An interface can also be used with other interfaces by using the extends keyword.
For example:
interface car
{
void start();
void stop();
}
Class Definition
o In this section, we define the class.
o It is a vital part of a Java program. Without the class, we cannot create any Java program.
o A Java program may contain more than one class definition.
o We use the class keyword to define the class.
o The class is a blueprint of a Java program. It contains information about user-defined methods,
variables, and constants.
o Every Java program has at least one class that contains the main() method.
For example:
class Student //class definition
{
}
Class Variables and Constants
o In this section, we define variables and constants that are to be used later in the program.
o In a Java program, the variables and constants are defined just after the class definition.
o The variables and constants store values of the parameters. It is used during the execution of the
program.
o We can also decide and define the scope of variables by using the modifiers. It defines the life of the
variables.
For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}
Main Method Class
o In this section, we define the main() method.
o It is essential for all Java programs. Because the execution of all Java programs starts from the main()
method.
o In other words, it is an entry point of the class. It must be inside the class.
o Inside the main method, we create objects and call the methods.

We use the following statement to define the main() method:


public static void main(String args[])
{
}
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
Methods and behavior
o In this section, we define the functionality of the program by using the methods.
o The methods are the set of instructions that we want to perform.
o These instructions execute at runtime and perform the specified task.

o For example:
public class Demo //class definition
{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to javatpoint");
}
//statements
}
}
When we follow and use the above elements in a Java program, the program looks like the following.

CheckPalindromeNumber.java
/*Program name: Palindrome*/
//Author's name:
/*Palindrome is number or string that will remains the same When we write that in reverse order. Some e
xample of palindrome is 393, 010, madam, etc.*/

//imports the Scanner class of the java.util package


import java.util.Scanner;

//class definition
public class CheckPalindromeNumber
{
//main method
public static void main(String args[])
{
//variables to be used in program
int r, s=0, temp;
int x; //It is the number variable to be checked for palindrome
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to check: ");
//reading a number from the user
x=sc.nextInt();
//logic to check if the number id palindrome or not
temp=x;
while(x>0)
{
r=x%10; //finds remainder
s=(s*10)+r;
x=x/10;
}
if(temp==s)
System.out.println("The given number is palindrome.");
else
System.out.println("The given number is not palindrome.");
}
}
Output:
Java Programming
JVM:
❖ 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.
❖ 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.
❖ The JVM performs the following main tasks: Loads code, Verifies code, Executes code, Provides
runtime environment.

15
Java Programming
JRE
❖ JRE is an acronym for Java Runtime Environment.
❖ 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.

16
Java Programming
JDK
❖ JDK is an acronym for Java Development Kit.
❖ The Java Development Kit (JDK) is a software development environment which is used to develop Java
applications and applets. It physically exists.
❖ It contains JRE + development tools.
❖ JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform
❖ The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc),
etc. to complete the development of a Java Application.

16
Java Programming

17
Java Programming
Keywords
❖ In Java, Keywords or Reserved words are the words in a language that are used for some internal process
or represent some predefined actions.
❖ These words are therefore not allowed to use as variable names or objects.

18
Java Programming

19
Java Programming

20
Java Programming

21
Java Programming

22
Java Programming

23
Java Programming

24
Java Programming

24
Java Programming
Java Variable:
❖ A variable is a container which holds the value while the Java program is executed.
❖ A variable is assigned with a data type.
❖ Variable is a name of memory location.

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

25
Java Programming
How to Declare Variables in Java?
❖We can declare variables in Java as pictorially depicted below as a visual aid.

❖We need to take care of two things that are:


1. datatype: Type of data that can be stored in this variable.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
1. Variable Initialization
2. Assigning value by taking input
How to Initialize Variables in Java?
❖It can be perceived with the help of 3 components that are as follows:

26
Java Programming

27
Java Programming

28
Java Programming

29
Java Programming
Example:

Add Two Numbers:

30
Java Programming
Widening:

Narrowing (Typecasting):

31
Java Programming
Overflow:

Adding Lower Type:

32
Java Programming

Data Types in Java:

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

1. Primitive data types:


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

33
1
Java Programming
1. Primitive Data Types:
❖Primitive data are only single values and have no special capabilities.
❖There are 8 primitive data types:

34
Java Programming
1. Boolean Data Type:
❖The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
❖The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

2. Byte Data Type:


❖The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving
memory in large arrays.

35
Java Programming
3. Short Data Type:
❖The short data type is a 16-bit signed two’s complement integer.
❖Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually
matters.

4. Integer Data Type:


❖ It is a 32-bit signed two’s complement integer.

36
Java Programming
5. Long Data Type:
❖The range of a long is quite large. The size of the Long Datatype is 8 bytes (64 bits).

6. Float Data Type:


❖Use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. The size of
the float data type is 4 bytes (32 bits).

7. Double Data Type:


❖For decimal values, this data type is generally the default choice. The size of the double data type is 8 bytes or
64 bits.

37
Java Programming

8. Char Data Type:

❖ The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).

38
Java Programming

39
Java Programming

40
Java Programming
2. Non-Primitive Data Type or Reference Data Types:
❖The Reference Data Types will contain a memory address of variable values.
❖Because the reference types won’t store the variable value directly in memory.
❖They are strings, objects, arrays, etc.
1. Strings:
❖Strings are defined as an array of characters.
❖The difference between a character array and a string in Java is,
• The string is designed to hold a sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities.
❖Unlike C/C++, Java strings are not terminated with a null character.

41
Java Programming

2. Class:
❖ A class is a user-defined blueprint or prototype from which objects are created.
❖ It represents the set of properties or methods that are common to all objects of one type.
❖ In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class
can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }. 42
Java Programming
3. Object:
❖An Object is a basic unit of Object-Oriented Programming and represents real-life entities.
❖A typical Java program creates many objects, which as you know, interact by invoking methods.
❖An object consists of :
• State: It is represented by the attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
• Identity: It gives a unique name to an object and enables one object to interact with other objects.
4. Interface:
❖ Like a class, an interface can have methods and variables, but the methods declared in an interface are by
default abstract (only method signature, no body).
• A Java library example is Comparator Interface. If a class implements this interface, then it can be
used to sort a collection.
5. Array:
❖ An Array is a group of like-typed variables that are referred to by a common name.
❖ In Java, all arrays are dynamically allocated.
43
Java Programming
Operators-Expression:
❖Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / 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: |, &, ^, ~ (OR, AND, XOR, Complement)
8. Shift Operators
1. 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.

44
Java Programming

45
Java Programming

46
Java Programming

47
Java Programming
An example program for all basic arithmetic operators:

48
Java Programming
2. Unary Operators:
❖The Java unary operators require only one operand. Unary operators are used to perform various
operations,
1. Incrementing/decrementing a value by one
2. Negating an expression
3. Inverting the value of a boolean
1. Unary minus(-):

49
Java Programming

50
Java Programming

51
Java Programming

52
Java Programming

53
Java Programming

54
Java Programming

55
Java Programming

56
Java Programming
3. 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.
Otherwise, the compiler will raise an error.
❖This means that the assignment operators have right to left associativity, i.e., the value given on
the right-hand side of the operator is assigned to the variable on the left.
❖Therefore, the right-hand side value must be declared before using it or should be a constant.
❖The general format of the assignment operator is,

Types of Assignment Operators:


1. Simple Assignment Operator - The Simple Assignment Operator is used with the “=” sign where
the left side consists of the operand and the right side consists of a value.
57
Java Programming

58
Java Programming

59
Java Programming

60
Java Programming

61
Java Programming

62
Java Programming

63
Java Programming
4. Relational Operators:
❖A bunch of binary operators used to check for relations between two operands, including equality, greater
than, less than, etc.
❖They return a boolean result after the comparison and are extensively used in looping statements as well as
conditional if-else statements and so on.
❖ The general format of representing relational operator is:

64
Java Programming

65
Java Programming

66
Java Programming

67
Java Programming

68
Java Programming

69
Java Programming

70
Java Programming
5. Logical Operators:
❖Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, i.e. the function similar
to AND gate and OR gate in digital electronics.
❖They are used to combine two or more conditions/constraints or to complement the evaluation of the original
condition under particular consideration.
❖One thing to keep in mind is, while using AND operator, the second condition is not evaluated if the first
one is false.
❖Where as while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND
and OR operators have a short-circuiting effect.
❖Used extensively to test for several conditions for making a decision.
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]

71
Java Programming
Example For Logical Operator :
❖Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for
all the situations.

72
Java Programming

73
Java Programming

74
Java Programming

75
Java Programming
6. Ternary Operator:
❖Java ternary operator is the only conditional operator that takes three operands.
❖It’s a one-liner replacement for the if-then-else statement and is used a lot in Java programming.

76
Java Programming

77
Java Programming
Example:

78
Java Programming
7. 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.

79
Java Programming

80
Java Programming

81
Java Programming

82
Java Programming
8. Shift Operator:
❖By shifting the bits of its first operand right or left, a shift operator performs bit manipulation on data.

83
Java Programming

84
Java Programming

85
Control Structures:

❖ In Java, the default execution flow of a program is a sequential order.


❖ Sequential order of execution flow may not be suitable for all situations.
❖ Sometimes, we may want to jump from one line to another, skip a part of the program, and execute a part of the program repeatedly.
❖ To solve this problem, java provides control statements.
❖ There are three types of control flow statements.
1. Selection Control Statements:

❖ In java, the selection statements are also known as decision making statements or branching statements.
❖ The selection statements are used to select a part of the program to be executed based on a condition.
❖ Java provides the following selection statements.
1. if statement
2. if-else statement
3. if-else if statement
4. nested if statement
5. switch statement

1) Simple if statement:

❖ In Java, we use the if statement to test a condition and decide the execution of a block of statements based on that condition result.
❖ If the condition is True, then the block of statements is executed and if it is False, then the block of statements is ignored.
❖ The syntax and execution flow of if the statement is as follows.
EX: Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}

Output: x + y is greater than 20


2) if-else statement

❖ The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
❖ The else block is executed if the condition of the if-block is evaluated as false.
Ex: Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}

Output: x + y is greater than 20


3) if-else if statement:

❖ Writing an if-statement inside the else of an if statement is called if-else-if statement.


❖ The general syntax of the if-else-if statement is as follows.

if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3; //executes when all the conditions are false
}
Ex: Student.java
public class Student
{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}
} Output: Delhi
4. Nested if statement:
❖ Writing an if statement inside another if-statement is called nested if statement.
❖ The general syntax of the nested if-statement is as follows.
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3; //executes when condition 2 is false
}
}
Ex: Student.java

class Nestedif
{
public static void main(String args[])
{
int a=10;
int b=20;
if(a==10){
if(b==20){
System.out.println("Nested If example");
}
}
}
}
5. Switch statement:
❖ In Java, 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.
❖ The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:

➢ The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
➢ Cases cannot be duplicate.
➢ Default statement is executed when any of the case doesn't match the value of expression. It is optional.
➢ Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed.
➢ While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will
also be a constant value.

Ex: Student.java
public class Student implements Cloneable
{
public static void main(String[] args)
{
int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}

Output: 2
2. Iterative Control 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.
❖ In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop

1. for loop:
❖ In Java, for loop is similar to C and C++.
❖ It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of
code.
❖ We use the for loop only when we exactly know the
number of times, we want to execute the block of code.
EX: Calculation.java
public class Calculattion
{
public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}

Output: The sum of first 10 natural numbers is 55


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.
❖ The syntax to use the for-each loop in java is:

Ex: Calculation.java
public class Calculation
{
public static void main(String[] args)
{
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names)
{
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
2. 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.
❖ It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
❖ If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
Ex: Calculation .java
public class Calculation
{
public static void main(String[] args)
{
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10)
{
System.out.println(i);
i = i + 2;
}
}
}
Output:
3. 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.


Ex: Calculation.java
public class Calculation
{
public static void main(String[] args)
{
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do
{
System.out.println(i);
i = i + 2;
}
while(i<=10);
}
}
Output:
3. Jump Statements:
❖ Jump statements are used to terminate a block or take the execution control to the next iteration.
❖ Java provides the following jump statements.
1. break
2. continue

1. break:
❖ As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next
statement outside a loop or switch statement.
❖ However, it breaks only the inner loop in the case of the nested loop.
❖ The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch
statement.
The following picture depicts the execution flow of the break statement:


Ex: Consider the following example in which we have used the break statement with the for loop:

public class BreakExample


{
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}
Ex: Break statement example with labeled for loop:
public class Calculation
{
public static void main(String[] args)
{
a:
for(int i = 0; i<= 10; i++)
{
b:
for(int j = 0; j<=15;j++)
{
c:
for (int k = 0; k<=20; k++)
{
System.out.println(k);
if(k==5)
{
break a;
} } } } }}
2. 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.


❖ Consider the following example to understand the functioning of the continue statement in Java.

public class ContinueExample


{
public static void main(String[] args)
{
for(int i = 0; i<= 2; i++)
{
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
System.out.println(j);
}
}
}
Output:
Type Casting:
 In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically.
 The automatic conversion is done by the compiler and manual conversion
performed by the programmer.

Type casting:

 There are two types of type casting:

1. Widening Type Casting


2. Narrowing Type Casting

1. Widening Type Casting:

 Converting a lower data type into a higher one is called widening type
casting.

 It is also known as implicit conversion or casting down.

 It is done automatically. It is safe because there is no chance to lose data.

 Both data types must be compatible with each other.


 The target type must be larger than the source type.
// Java program to demonstrate Widening TypeCasting

import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 10;
// Wideing TypeCasting (Automatic Casting)from int to long
long l = i;
// Wideing TypeCasting (Automatic Casting)from int to double
double d = i;
System.out.println("Integer: " + i);
System.out.println("Long: " + l);
System.out.println("Double: " + d);
}
}

Output:

Integer: 10
Long: 10
Double: 10.0

2. Narrow Type Casting:

 The process of downsizing a bigger data type into a smaller one is known as
narrowing type casting.
 Casting up or explicit type casting are other names for it.
 It doesn’t just happen by itself. If we don’t explicitly do that, a compile-time
error will occur.
 Narrowing type casting is unsafe because data loss might happen due to the
lower data type’s smaller range of permitted values.
 A cast operator assists in the process of explicit casting.
// Java Program to demonstrate Narrow type casting
import java.io.*;
class GFG {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;
System.out.println("Original Value before Casting"+ i);
System.out.println("After Type Casting to short"+ j);
System.out.println("After Type Casting to int"+ k);
}
}

Output:

Original Value before Casting100.245


After Type Casting to short 100
After Type Casting to int 100

Types of Explicit Casting:

 Mainly there are two types of Explicit Casting:

1. Explicit Upcasting
2. Explicit Downcasting

1. Explicit Upcasting:

 Upcasting is the process of casting a subtype to a supertype in the


inheritance tree’s upward direction.

 When a sub-class object is referenced by a superclass reference variable, an


automatic process is triggered without any further effort.

// Java Program to demonstrate Explicit Upcasting

import java.io.*;
class Animal {
public void makeSound()
{
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound()
{
System.out.println("The dog barks");
}
public void fetch()
{
System.out.println("The dog fetches a ball");
}
}
class GFG {
public static void main(String[] args)
{
// Upcasting
Animal animal = new Dog();
// Calls the overridden method in Dog class
animal.makeSound();
// This would give a compile error as fetch() is not a method in
Animal class animal.fetch();
}
}

Output:

The dog barks

2. Explicit Downcasting:
 When a subclass type refers to an object of the parent class, the process is
referred to as downcasting.
 If it is done manually, the compiler issues a runtime ClassCastException
error. It can only be done by using the instanceof operator.
 Only the downcast of an object that has already been upcast is possible.
// Java Program to demonstrate Explicit downcasting
import java.io.*;
class Animal {
public void eat()
{
System.out.println("The animal is eating.");
}
}
class Cat extends Animal {
public void meow()
{
System.out.println("The cat is meowing.");
}
}

class GFG {
public static void main(String[] args)
{
Animal animal = new Cat();
animal.eat();
// Explicit downcasting
Cat cat = (Cat)animal;
cat.meow();
}
}

Output:

The animal is eating.


The cat is meowing.
Classes and Objects:
❖ In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and
entities.
❖ The class represents a group of objects having similar properties and behavior.

Classes:
❖ A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes.
❖ It is a user-defined blueprint or prototype from which objects are created.
❖ Ex: Student is a class while a particular student named Ravi is an object.
Properties of Classes:
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and group of methods.
4. A Class can contain:
❖ Data member
❖ Method
❖ Constructor
❖ Nested Class
❖ Interface
Class Declaration:
// Java Program for class example
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Output:
0
null
Components of Java Classes:

In general, class declarations can include these components, in order:


1. Modifiers : A class can be public or has default access.
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass)
one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
6. Body: The class body is surrounded by braces, { }.

Objects:
❖ Objects are the instances of a class that are created to use the attributes and methods of a class.
❖ A typical Java program creates many objects, which as you know, interact by invoking methods.
❖ An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other objects.
Create an Object:
❖ In Java, an object is created from a class. We have already created the class named Add, so now we can use this to create objects.
❖ To create an object of Add, specify the class name, followed by the object name, and use the keyword new:

Example:
Create an object called "myObj" and print the value of x:

public class Add {

int x = 5;

public static void main(String[] args) {

Add myObj = new Add();

System.out.println(myObj.x);

}}

Output:
5
Multiple Objects:
❖ You can create multiple objects of one class:
Example:

Create two objects of Add:

public class Add {

int x = 5;

public static void Add(String[] args) {

Add myObj1 = new Add(); // Object 1

Add myObj2 = new Add(); // Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

Output:
5
5
Difference between Java Class and Objects:
Class Object

Class is the blueprint of an object. It is used to create


An object is an instance of the class.
objects.

No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.

An object is a real-world entity such as a book, car,


A class is a group of similar objects.
etc.

Class is a logical entity. An object is a physical entity.

A class can only be declared once. Objects can be created many times as per requirement.

Objects of the class car can be BMW, Mercedes,


An example of class can be a car.
Ferrari, etc.
Methods:

❖ A method is a block of code or collection of statements or a set


of code grouped together to perform a certain task or operation.
❖ It is used to achieve the reusability of code. We write a method
once and use it many times. We do not require to write code
again and again.
❖ It also provides the easy modification and readability of code
by adding or removing a chunk of code.
❖ The method is executed only when we call or invoke it.

Method Declaration:

❖ The method declaration provides information about method .


It has six components that are known as method header,
❖ Method Signature: Every method has a method signature. It is a
part of the method declaration. It includes the method
name and parameter list.
❖ Access Specifier: Access specifier or modifier is the access type
of the method. It specifies the visibility of the method. Java
provides four types of access specifier:
➢ Public: The method is accessible by all classes when we use
public specifier in our application.
➢ Private: When we use a private access specifier, the method
is accessible only in the classes in which it is defined.
➢ Protected: When we use protected access specifier, the
method is accessible within the same package or subclasses
in a different package.

➢ Default: When we do not use any access specifier in the


method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
❖ Return Type: Return type is a data type that the method returns.
It may have a primitive data type, object, collection, void, etc. If
the method does not return anything, we use void keyword.
❖ Method Name: It is a unique name that is used to define the
name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
❖ Parameter List: It is the list of parameters separated by a
comma and enclosed in the pair of parentheses. It contains the
data type and variable name. If the method has no parameter,
left the parentheses blank.
❖ Method Body: It is a part of the method declaration. It contains
all the actions to be performed. It is enclosed within the pair
of curly braces.
Naming a Method:

❖ While defining a method, remember that the method name must


be a verb and start with a lowercase letter.
❖ In the multi-word method name, the first letter of each word
must be in uppercase except the first word.

❖ It is also possible that a method has the same name as another


method name in the same class, it is known as method
overloading.

For example:

➢ Single-word method name: sum(), area()


➢ Multi-word method name: areaOfCircle(),
stringComparision()
Types of Method:

There are two types of methods in Java:

a. Predefined Method
b. User-defined Method

A. Predefined Method:

❖ In Java, predefined methods are the method that is already


defined in the Java class libraries is known as predefined
methods. It is also known as the standard library
method or built-in method.
❖ We can directly use these methods just by calling them in the
program at any point. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to
the corresponding method runs in the background that is already
stored in the library.
❖ Each and every predefined method is defined inside a class. Such
as print() method is defined in the java.io.PrintStream class. It
prints the statement that we write inside the method.
❖ For example, print("Java"), it prints Java on the console.
Example: Demo.java

class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.
max(9,7));
}
}

Output:
The maximum number is: 9
B. User-defined Method:

❖ The method written by the user or programmer is known as a


user-defined method. These methods are modified according to
the requirement.

How to Create a User-defined Method,

➢ Let's create a user defined method that checks the number is


even or odd. First, we will define the method.
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
❖ We have defined the above method named findEvenodd(). It has
a parameter num of type int.
❖ The method does not return any value that's why we have
used void.
❖ The method body contains the steps to check the number is
even or odd.
❖ If the number is even, it prints the number is even, else prints
the number is odd.
How to Call or Invoke a User-defined Method

❖ Once we have defined a method, it should be called.


❖ The calling of a method in a program is simple.
❖ When we call or invoke a user-defined method, the program
control transfers to the called method.

import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
❖ In the above code snippet, as soon as the compiler reaches at
line findEvenOdd(num), the control transfer to the method and
gives the output accordingly.
Ex: Addition.java

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2)//n1 and n2 are formal para
meters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

Output:

The sum of a and b is= 24


Static Method:

❖ A method that has static keyword is known as static method.


❖ In other words, a method that belongs to a class rather than
an instance of a class is known as a static method.
❖ We can also create a static method by using the
keyword static before the method name.
❖ The main advantage of a static method is that we can call it
without creating an object.
❖ It can access static data members and also change the value
of it.
❖ The best example of a static method is the main() method.

Example: Display.java

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}

Output:

It is an example of a static method.


Instance Method:

❖ The method of the class is known as an instance method.


❖ It is a non-static method defined in the class.
❖ Before calling or invoking the instance method, it is necessary
to create an object of its class.

Example:
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample()
;
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//userdefined method because we have not used static keyword

public int add(int a, int b)


{
s = a+b;
//returning the sum
return s;
}
}

Output:

The sum is: 25


Abstract Method:

❖ The method that does not have method body is known as


abstract method. In other words, a method without an
implementation is known as an abstract method.
❖ It always declares in the abstract class. It means the class
itself must be abstract if it has abstract method.
❖ To create an abstract method, we use the keyword abstract.

Syntax:

abstract void method_name();

Ex: Demo.java

abstract class Demo //abstract class


{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display(); }
}

Output:

Abstract method...
Constructors

❖ A constructor in Java is similar to a method that is invoked when


an object of the class is created.
❖ Unlike Java methods, a constructor has the same name as that of
the class and does not have any return type.
For example,
class Test {
Test() {
// constructor body
}
}

Here,
❖ Test() is a constructor. It has the same name as that of the class
and doesn't have a return type.

Example:
class Cons {
private String name;

// constructor
Cons() {
System.out.println("Constructor Called:");
name = "Prajesh";
}

public static void main(String[] args) {

// constructor is invoked while creating an object of the Cons class


Cons obj = new Cons();
System.out.println("The name is " + obj.name);
}
}
Output:
Constructor Called:
The name is Prajesh
Types of Constructor

In Java, constructors can be divided into three types:


1. No-Arg Constructor

2. Parameterized Constructor

3. Default Constructor

1. No-Arg Constructors:
❖ Similar to methods, a Java constructor may or may not have any
parameters (arguments).

❖ If a constructor does not accept any parameters, it is known as a


no-argument constructor.

For example,

private Constructor()
{
// body of the constructor
}
For example: Java Private No-arg Constructor
class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Output:

Constructor is called
Value of i: 5

Example: Java Public no-arg Constructors

class Company {
String name;
// public constructor
public Company() {
name = "Prabha";
}
}
class Main {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
Output:

Company name = Prabha


2. Parameterized Constructor:

❖ A Java constructor can also accept one or more parameters. Such


constructors are known as parameterized constructors
(constructors with parameters).

Example: Parameterized Constructor

class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output:

Java Programming Language


Python Programming Language
C Programming Language

In the above example,


❖ We have created a constructor named Main() .

❖ Here, the constructor takes a single parameter. Notice the


expression:

Main obj1 = new Main("Java");

❖ Here, we are passing the single value to the constructor.


❖ Based on the argument passed, the language variable is initialized
inside the constructor.

3. Default Constructor:

❖ If we do not create any constructor, the Java compiler


automatically creates a no-arg constructor during the
execution of the program. This constructor is called the default
constructor.

Example: Default Constructor

class Main {

int a;
boolean b;

public static void main(String[] args) {

// calls default constructor


Main obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:

Default Value:
a = 0
b = false

❖ Here, we haven't created any constructors. Hence, the Java compiler


automatically creates the default constructor.

❖ The default constructor initializes any uninitialized instance variables


with default values.
Type Default Value

boolean false

byte 0

short 0

int 0

long 0L

char \u0000

float 0.0f

double 0.0d

object Reference null

Important Notes on Java Constructors

❖ Constructors are invoked implicitly when you instantiate objects.


❖ The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. A Java constructor must not have a return type.
❖ If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time.
❖ The default constructor initializes instance variables with default values.
For example, the int variable will be initialized to 0
❖ Constructortypes:
1. No-Arg Constructor - a constructor that does not accept any arguments
2. Parameterized constructor - a constructor that accepts arguments
3. Default Constructor - a constructor that is automatically created by the Java
compiler if it is not explicitly defined.
❖ A constructor cannot be abstract or static or final.
❖ A constructor can be overloaded but can not be overridden.
Constructors Overloading in Java:
❖ Similar to Java method overloading, we can also create two or more
constructors with different parameters. This is called constructor overloading.

Example: Constructor Overloading


class Main {
String language;
// constructor with no parameter
Main() {
this.language = "Java";
}

// constructor with a single parameter


Main(String language) {
this.language = language;
}

public void getName() {


System.out.println("Programming Language: " + this.language);
}

public static void main(String[] args) {


// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}
}
Output:

Programming Language: Java


Programming Language: Python
Polymorphism in Java

Polymorphism is considered one of the important features of Object-Oriented


Programming.
Polymorphism allows us to perform a single action in different ways.

Types of Java Polymorphism


• Compile-time Polymorphism
• Runtime Polymorphism

Compile-Time Polymorphism in Java


It is also known as static polymorphism. This type of polymorphism is achieved
by function/method overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.

The runtime polymorphism can be achieved by method overriding.


The child class has the same method as declared in the parent class.
It means if the child class provides the specific implementation of the method
that has been provided by one of its parent classes then it is known as method
overriding.
Method Overloading

❖ In Java, two or more methods may have the same name if they
differ in parameters (different number of parameters, different
types of parameters, or both).
❖ These methods are called overloaded methods and this feature is
called method overloading.

For example:

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

Here, the func() method is overloaded.


These methods have the same name but accept different arguments.
Note: The return types of the above methods are not the same.
It is because method overloading is not associated with return types.
Overloaded methods may have the same or different return types, but
they must differ in parameters.
Why method overloading?

❖ Suppose, you have to perform the addition of given numbers but


there can be any number of arguments (let’s say either 2 or 3
arguments for simplicity).
❖ In order to accomplish the task, you can create two
methods sum2num(int, int) and sum3num(int, int, int) for two
and three parameters respectively. However, other programmers,
as well as you in the future may get confused as the behavior of
both methods are the same but they differ by name.
❖ The better way to accomplish this task is by overloading
methods. And, depending upon the argument passed, one of the
overloaded methods is called. This helps to increase the readability
of the program.
How to perform method overloading in Java?

Here are different ways to perform method overloading:

1. Overloading by changing the number of parameters:

class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}
Output:

Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of parameters:

class MethodOverloading {

// this method accepts int


private static void display(int a){
System.out.println("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
System.out.println("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}
Output:

Got Integer data.


Got String object.

❖ Here, both overloaded methods accept one argument.


❖ However, one accepts the argument of type int whereas other
accepts String object.
Look at a real-world example:

class HelperService {

private String formatNumber(int value) {


return String.format("%d", value);
}

private String formatNumber(double value) {


return String.format("%.3f", value);
}

private String formatNumber(String value) {


return String.format("%.2f", Double.parseDouble(value));
}

public static void main(String[] args) {


HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}

Output:
500
89.993
550.00
Important Points

❖ Two or more methods can have the same name inside the
same class if they accept different arguments. This feature is
known as method overloading.

❖ Method overloading is achieved by either:

➢ changing the number of arguments.

➢ or changing the data type of arguments.

❖ It is not method overloading if we only change the return type of


methods.

❖ There must be differences in the number of parameters.


this Keyword and Static:

this – keyword:
1. In Java, this is a reference variable that refers to the current
object.

Usage of Java this keyword:

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.

1) this: to refer current class instance variable

❖ The this keyword can be used to refer current class instance variable.
❖ If there is ambiguity between the instance variables and parameters, this
keyword resolves the problem of ambiguity.
Ex: The example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and
instance variable.

class Student
{
int rollno;
String name;
float fee;

Student(int rollno, String name, float fee)


{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"Raja",7000f);
Student s2=new Student(112,"Praba",9000f);
s1.display();
s2.display();
}
}

Output:

111 Raja 7000.0


112 Praba 9000.0
2) this: to invoke current class method
❖ You may invoke the method of the current class by using this
keyword. If you don't use ‘this’ keyword, compiler automatically
adds this keyword while invoking the method.
Example:

Program:
class A{

void m(){System.out.println("hello m");}

void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}

class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:

hello n
hello m

3) this(): to invoke current class constructor

❖ The this() constructor call can be used to invoke the current class
constructor.
❖ It is used to reuse the constructor. In other words, it is used for
constructor chaining.

Ex: Calling default constructor from parameterized constructor


class A
{
A( )
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}
}

Output:

hello a
10
4) this: to pass as an argument in the method

❖ this keyword can also be passed as an argument in the method. It is


mainly used in the event handling.

Example:

class S2{

void m(S2 obj){


System.out.println("method is invoked");
}

void p(){
m(this);
}
public static void main(String args[]) {
S2 s1 = new S2();
s1.p();
}
}

Output:

method is invoked
5) this: to pass as argument in the constructor call
❖ We can pass the this keyword in the constructor also. It is useful if we
have to use one object in multiple classes.
Example:
class B
{
A4 obj;

B(A4 obj) {
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4
{
int data=10;
A4( )
{
B b=new B(this);
b.display();
}
public static void main(String args[])
{
A4 a=new A4();
}
}

Output: 10
6). This: keyword can be used to return current class
instance
❖ We can return this keyword as an statement from the method.
❖ In such case, return type of the method must be the class type (non-
primitive).

Syntax of this that can be returned as a statement:

Example: of this keyword that you return as a statement from the method
class A
{
A getA() {
return this; }
void msg(){System.out.println("Hello java");
}
}
class Test1{
public static void main(String args[])
{ new A().getA().msg();
}
}

Output:

Hello java
static keyword:

❖ The static keyword in Java is used for memory management


mainly.
❖ We can apply static keyword with variables, methods, blocks
and nested classes.
❖ The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
1). Java static variable:

❖ If you declare any variable as static, it is known as a static


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

Advantages:

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


Example:
//Java Program to demonstrate the use of static variable
class Student {
int rollno; //instance variable
String name;
static String college ="ITS"; //static variable

//constructor
Student(int r, String n){
rollno = r;
name = n;
}

//method to display the values


void display (){System.out.println(rollno+" "+name+" "+college);}
}

//Test class to show the values of objects


public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");

//we can change the college of all objects by the single line of code
Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
2) Java static method:

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


static method.

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


class.
➢ A static method can be invoked without the need for creating
an instance of a class.
➢ A static method can access static data member and can change
the value of it.
Example:
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";

//static method to change the value of static variable


static void change(){
college = "BBDIT"; }

//constructor to initialize the variable


Student(int r, String n){
rollno = r;
name = n; }

//method to display values


void display(){System.out.println(rollno+" "+name+" "+college);}
}

//Test class to create and display the values of object


public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Restrictions for the static method:

❖ There are two main restrictions for the static method. They are:

1. The static method can not use non-static data member or call
non-static method directly.
2. this and super cannot be used in static context.

Ex:
class A{
int a=40; //non static
public static void main(String args[]){
System.out.println(a); } }

Output:
Compile Time Error
Why is the Java main method static?

❖ It is because the object is not required to call a static method. If


it were a non-static method, JVM creates an object first then
call main() method that will lead the problem of extra memory
allocation.
3) Java static block:
❖ Is used to initialize the static data member.

❖ It is executed before the main method at the time of


classloading.

Example:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
} }

Output:
static block is invoked
Hello main
Arrays
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.
❖ In Java, array is an object of a dynamically generated class.
❖ Java array inherits the Object class.
❖ We can store primitive values or objects in an array in Java.
❖ Like C/C++, we can also create single dimentional or multidimentional arrays
in Java.
❖ Moreover, Java provides the feature of anonymous arrays which is not
available in C/C++.

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

Disadvantages:
❖ Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array:
❖ There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array

1. Single Dimensional Array:


Syntax to Declare an Array:

Instantiation of an Array:

❖ Simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
Declaration, Instantiation and Initialization of Array:
❖ We can declare, instantiate and initialize the java array together by:

Output:

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

The syntax of the for-each loop:


❖ Example of print the elements of Java array using the for-each loop.

Output:

Passing Array to a Method:


❖ We can pass the java array to method so that we can reuse the same logic on
any array.
❖ Simple Example to get the minimum number of an array using a method.

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

Output:

Returning Array from the Method:


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

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

Syntax to Declare Multidimensional Array:

Example to instantiate Multidimensional Array:

Example to initialize Multidimensional Array:


Example of Multidimensional Java Array:
❖ Simple example to declare, instantiate, initialize.

Output:
Jagged Array in Java:
❖ If we are creating odd number of columns in a 2D array, it is known as a
jagged array.
❖ In other words, it is an array of arrays with different number of columns.

Output:
Addition of 2 Matrices:

❖ A simple example that adds two matrices.

Output:
Multiplication of 2 Matrices:
❖ In the case of matrix multiplication, a one-row element of the first matrix is
multiplied by all the columns of the second matrix which can be understood by
the image given below.
❖ A simple example to multiply two matrices of 3 rows and 3 columns.

Output:
String
❖ A string is a sequence of characters surrounded by double
quotations.
❖ In a java programming language, a string is the object of a built-in class
String.
❖ In the background, the string values are organized as an array of a
character data type.
❖ The string created using a character array can not be extended. It does
not allow to append more characters after its definition, but it can be
modified.
Let's look at the following example java code.

❖ The String class is defined in the package java.lang package.


❖ The String class implements Serializable, Comparable, and
CharSequence interfaces.
❖ The string created using the String class can be extended. It allows us
to add more characters after its definition, and also it can be modified.
❖ Let's look at the following example java code.
Example:
Creating String object in java:
❖ In java, we can use the following two ways to create a string
object.
➢ Using string literal
➢ Using String constructor

Example:

❖ The String class constructor accepts both string and character


array as an argument.

String handling methods:


❖ In java programming language, the String class contains various
methods that can be used to handle string data values.
❖ It containg methods like concat( ), compareTo( ), split( ), join( ),
replace( ), trim( ), length( ), intern( ), equals( ), comparison( ),
substring( ), etc.,
The following table depicts all built-in methods of String class in java:
Example:
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Tutorials";
String siteName = "www.btechsmartclass.com";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Ends with '.com': " + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}

Output:
Difference between Array and String:

S.NO. Array String

An array is a data structure


A string is basically treated as an
that stores a collection of
01. object which represents a sequence
elements of the same data
of characters. An array
type.

Array can hold any of the data But, the String can hold only a char
02.
types. data type.

A string class contains a pointer to


The elements of the array are
some part of the heap memory
03. stored in a contiguous memory
where the actual contents of the
location.
string are stored in memory.

Java array not ended with a


null character, the end element But by default String is ended with
04.
of the array is the last element null (‘\0’) character in Java.
of the array.

05. Arrays are mutable. Strings are immutable.

06. The length of the array is fixed. The size of the string is not fixed.
String Buffer-String Handling Mechanism

StringBuffer Class:
 Java StringBuffer class is used to create mutable (modifiable) String
objects.
 The StringBuffer class in Java is the same as String class except it
is mutable i.e. it can be changed.

Important Constructors of StringBuffer Class:


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int It creates an empty String buffer with the specified capacity as


capacity) length.

Important methods of StringBuffer class:


Modifier and Method Description
Type

It is used to append the specified string with this


public
string. The append() method is overloaded like
synchronized append(String s)
append(char), append(boolean), append(int),
StringBuffer
append(float), append(double) etc.

It is used to insert the specified string with this


public string at the specified position. The insert()
insert(int offset, String
synchronized method is overloaded like insert(int, char),
s)
StringBuffer insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public
replace(int startIndex, It is used to replace the string from specified
synchronized
int endIndex, String str) startIndex and endIndex.
StringBuffer

public
delete(int startIndex, It is used to delete the string from specified
synchronized
int endIndex) startIndex and endIndex.
StringBuffer

public
synchronized reverse() is used to reverse the string.
StringBuffer

public int capacity() It is used to return the current capacity.

ensureCapacity(int It is used to ensure the capacity at least equal to


public void
minimumCapacity) the given minimum.

It is used to return the character at the specified


public char charAt(int index)
position.

It is used to return the length of the string i.e. total


public int length()
number of characters.

substring(int It is used to return the substring from the


public String
beginIndex) specified beginIndex.

substring(int
It is used to return the substring from the
public String beginIndex, int
specified beginIndex and endIndex.
endIndex)

What is a mutable String?


 A String that can be modified or changed is known as mutable String.
 StringBuffer and StringBuilder classes are used for creating mutable
strings.

1) StringBuffer Class append() Method:


 The append() method concatenates the given argument with this
String.
Example:
class StringBufferExample{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output: Hello Java

2) StringBuffer insert() Method:


 The insert() method inserts the given String with this string at the
given position.

Example:
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello
}
}

Output: HJavaello

3) StringBuffer replace() Method:


 The replace() method replaces the given String from the specified
beginIndex and endIndex.
Example:
class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}

Output: HJavalo

4) StringBuffer delete() Method:


 The delete() method of the StringBuffer class deletes the String
from the specified beginIndex to endIndex.

Example:
class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output: Hlo
5) StringBuffer reverse() Method:
 The reverse() method of the StringBuilder class reverses the
current String.

Example:
class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output: olleH

6) StringBuffer capacity() Method:


 The capacity() method of the StringBuffer class returns the current
capacity of the buffer.
 The default capacity of the buffer is 16. If the number of character
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2.
 For example if your current capacity is 16, it will be (16*2)+2=34.

Example:

class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:

16
16
34

7) StringBuffer ensureCapacity() method:

 The ensureCapacity() method of the StringBuffer class ensures that


the given capacity is the minimum to the current capacity.
 If it is greater than the current capacity, it increases the capacity by
(oldcapacity*2)+2.
 For example if your current capacity is 16, it will be (16*2)+2=34.

Example:

class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:

16
16
34
34
70
Wrapper Classes and Command line arguments
Wrapper Classes:
➢ A Wrapper class in Java is a class whose object wraps or contains primitive
data types.
➢ When we create an object to a wrapper class, it contains a field and in this field,
we can store primitive data types.
➢ The wrapper class in Java provides the mechanism to convert primitive
data types into object and object into primitive data types.

Need of Wrapper Classes:

1. They convert primitive data types into objects. Objects are needed if
we wish to modify the arguments passed into a method (because primitive
types are passed by value).

2. The classes in java.util package handles only objects and hence


wrapper classes help in this case also.

3. Data structures in the Collection framework, such


as ArrayList and Vector, store only objects (reference types) and not
primitive types.

4. An object is needed to support synchronization in multithreading.

Advantages of Wrapper Classes:


1. Collections allowed only object data.
2. On object data we can call multiple methods compareTo(), equals(),
toString()
3. Cloning process only objects.
4. Object data allowed null values.
5. Serialization can allow only object data.
Autoboxing:
➢ The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing.
➢ For example, byte to Byte, char to Character, int to Integer, long to Long, float
to Float, boolean to Boolean, double to Double, and short to Short.
➢ Since Java 5, we do not need to use the valueOf() method of wrapper classes
to convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects , Autoboxing .
public class WrapperExample1
{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a;//autoboxing, compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output: 20 20 20
Unboxing:
➢ The automatic conversion of wrapper type into its corresponding primitive
type is known as unboxing. It is the reverse process of autoboxing.
➢ Since Java 5, we do not need to use the intValue() method of wrapper classes
to convert the wrapper type into primitives.
Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int explicitly
int j=a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}
Output:

333

Java Wrapper classes Example:


//Java Program to convert all primitives into its corresponding
wrapper objects and vice-versa
public class WrapperExample3
{
public static void main(String args[])
{
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}
}
Output:

---Printing object values---


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true
Command line arguments:
➢ The java command-line argument is an argument i.e. passed at the time of
running the java program.
➢ The arguments passed from the console can be received in the java
program and it can be used as an input.
➢ So, it provides a convenient way to check the behavior of the program for the
different values.
➢ You can pass N (1, 2, 3, and so on) numbers of arguments from the command
prompt.
Simple Example:
➢ In this example, we are receiving only one argument and printing it.
➢ To run this java program, you must pass at least one argument from the
command prompt.

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Compile by > javac CommandLineExample.java
Run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo


Example of command-line argument that prints all the values:

➢ In this example, we are printing all the arguments passed from the command-
line.
➢ For this purpose, we have traversed the array using for loop.

class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Compile by > javac A.java
Run by > java A sonoo jaiswal 1 3 abc

Output:
sonoo
jaiswal
1
3
abc
Java API Packages
Java Package:
➢ 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.

Advantages:
1) The Java package is used to categorize the classes and interfaces to
be easily maintained.
2) The Java package provides access protection.
3) The Java package removes naming collision.
A simple example of a Java package:
➢ The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
How to compile Java package
➢ syntax is given below:
javac -d directory javafilename
For example:

javac -d . Simple.java
Note:
• The -d switch specifies the destination where to put the generated
class file.
• You can use any directory name like /home (in case of Linux), d:/abc
(in case of windows), etc.
• If you want to keep the package within the same directory, you can
use it. (dot).
• The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.
How to run the java package program
➢ You need to use fully qualified name e.g. mypack.Simple etc to run the
class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple

Output: Welcome to package

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.
1) Using packagename.*
➢ If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
➢ The import keyword is used to make the classes and interface of
another package accessible to the current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Output: Hello
2) Using packagename.classname
➢ If you import package.classname then only declared class of this
package will be accessible.

Example of package by import package.classname


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Output: Hello
3) Using fully qualified name
➢ If you use fully qualified name then only declared class of this
package will be accessible.
➢ Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
➢ It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.

//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");
}
}

//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

Output: Hello
Note: If you import a package, subpackages will not be imported.
Note: Sequence of the program must be package then import then class.

Subpackage in Java:
➢ Package inside the package is called the subpackage. It should be
created to categorize the package further.
➢ Let's take an example, Sun Microsystem has definded a package
named java that contains many classes like System, String, Reader,
Writer, Socket etc.
➢ These classes represent a particular group e.g. Reader and Writer
classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on.
➢ So, Sun has subcategorized the java package into subpackages such
as lang, net, io etc. and put the Input/Output related classes in io
package, Server and ServerSocket classes in net packages and so on.
Note: The standard of defining package is domain.company.package e.g.
com.javatpoint.bean or org.sssit.dao.
Example of Subpackage:
package com.javatpoint.core;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output: Hello subpackage


How to send the class file to another directory or drive?
➢ There is a scenario, I want to put the class file of A.java source file in
classes folder of c: drive.

For example:

//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java

To Run:
➢ To run this program from e:\source directory, you need to set classpath
of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
➢ The -classpath switch can be used with javac and java tool.
➢ To run this program from e:\source directory, you can use -classpath
switch of java that tells where to look for class file.
For example:
e:\sources> java -classpath c:\classes mypack.Simple

Output: Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent
• Temporary
• By setting the classpath in the command prompt
• By -classpath switch
• Permanent
• By setting the classpath in the environment variables
• By creating the jar file, that contains all the class files, and
copying the jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be
saved by the public class name.
//save as C.java otherwise Compilte Time Error
class A
{
}
class B
{
}
public class C
{
}
Basics of Inheritance - Forms of Inheritance

Inheritance:
➢ Inheritance is a mechanism of driving a new class from an existing class.
The existing (old) class is known as base class or super class or parent
class.
➢ The new class is known as a derived class or sub class or child class. It
allows us to use the properties and behavior of one class (parent) in another
class (child).
➢ A class whose properties are inherited is known as parent class and a
class that inherits the properties of the parent class is known as child class.
➢ Thus, it establishes a relationship between parent and child class that
is known as parent-child or Is-a relationship.
➢ Suppose, there are two classes named Father and Child and we want to
inherit the properties of the Father class in the Child class.
➢ We can achieve this by using the extends keyword.

//inherits the properties of the Father class


class Child extends Father
{
//functionality
}
When we should use inheritance?
➢ Inheritance provides the reusability of code especially when there is a
large scale of code to reuse.
➢ It also establishes the relationship between different classes that is known
as a Is-a relationship.
➢ We can also use it if we want to achieve method overriding.

Points to Remember:

➢ Constructor cannot be inherited in Java.


➢ Private members do not get inherited in Java.
➢ Assign parent reference to child objects.
➢ Constructors get executed because of super() present in the constructor.
Types of Inheritance:
Java supports the following four types of inheritance:
➢ Single Inheritance
➢ Multi-level Inheritance
➢ Hierarchical Inheritance
➢ Hybrid Inheritance

Note: Multiple inheritance is not supported in Java.


1. Single Inheritance:
➢ In single inheritance, a sub-class is derived from only one super class.
➢ It inherits the properties and behavior of a single-parent class.
Sometimes it is also known as simple inheritance.
In the above figure, Employee is a parent class and Executive is a child
class. The Executive class inherits all the properties of the Employee
class.

Example: Executive.java
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Output:

Total salary credited: 414408.0


Bonus of six months: 18000.0
2. Multi-level Inheritance
➢ In multi-level inheritance, a class is derived from a class which is also
derived from another class is called multi-level inheritance.
➢ In simple words, we can say that a class that has more than one parent
class is called multi-level inheritance.
➢ Note that the classes must be at different levels. Hence, there exists a
single base class and single derived class but multiple intermediate base
classes.

In the above figure, the class Marks inherits the members or methods of
the class Students. The class Sports inherits the members of the class
Marks.
Therefore, the Student class is the parent class of the class Marks and the
class Marks is the parent of the class Sports.
Hence, the class Sports implicitly inherits the properties of the Student
along with the class Marks.
Example: MultilevelInheritanceExample.java
//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}

Output:

registration number= 0987


marks= 78.0
score= 68.7
3. Hierarchical Inheritance:
➢ If a number of classes are derived from a single base class, it is
called hierarchical inheritance.

In the above figure, the classes Science, Commerce, and Arts inherit a single
parent class named Student.
Example: HierarchicalInheritanceExample.java
//parent class
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}

Output:

The method of the class Student invoked.


The method of the class Student invoked.
The method of the class Student invoked.
4. Hybrid Inheritance:
➢ Hybrid means consist of more than one. Hybrid inheritance is the
combination of two or more types of inheritance.

In the below figure, GrandFather is a super class. The Father class inherits
the properties of the GrandFather class.

Since Father and GrandFather represents single inheritance. Further, the


Father class is inherited by the Son and Daughter class.
Thus, the Father becomes the parent class for Son and Daughter.
These classes represent the hierarchical inheritance. Combinedly, it denotes
the hybrid inheritance.
Example: Daughter.java
//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
Output:

I am daughter.
Multiple Inheritance (not supported):
➢ Java does not support multiple inheritances due to ambiguity. For
example, consider the following Java program.

Example: Demo.java
class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a sce
nario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}

Output:
The above code gives error because the compiler cannot decide which
message() method is to be invoked. Due to this reason, Java does not
support multiple inheritances at the class level but can be achieved through
an interface.
Super keyword – Final Keywords, Method Overriding
Super keyword:

➢ The super keyword in Java is a reference variable that refers to the immediate parent
class object.
➢ Whenever you create the instance of a subclass, an instance of parent class is
created implicitly which is referred by super reference variable.

Usage of Java super Keyword:

1. to refer immediate parent class instance variable.


2. to invoke immediate parent class method.
3. super() to invoke immediate parent class constructor.

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


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

Example:
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
} }
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}
Output:

black
white

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

2) super can be used to invoke parent class method

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

Example:

class Animal
{
void eat()
{
System.out.println("eating...");
} }
class Dog extends Animal
{
void eat(){System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
} }
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
} }
Output:

eating...
barking...

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

3) super is used to invoke parent class constructor

➢ The super keyword can also be used to invoke the parent class
constructor.

Example:

class Animal
{
Animal()
{
System.out.println("animal is created");
} }
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
} }
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}}
Output:

animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if
there is no super() or this().

As we know well the default constructor is provided by the compiler


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

Example: Another example of super keyword where super() is provided by


the compiler implicitly.
class Animal
{
Animal(){System.out.println("animal is created");
}}
class Dog extends Animal
{
Dog()
{
System.out.println("dog is created");
} }
class TestSuper4
{
public static void main(String args[])
{
Dog d=new Dog();
} }

Output:

animal is created
dog is created
Final Keywords:

➢ The final keyword in Java is used to restrict the user. The Java final keyword
can be used in many contexts.
The final can be:
1. variable
2. method
3. class
➢ The final keyword can be applied to the variables, a final variable that has no
value is called blank final variable or uninitialized final variable.
➢ It can be initialized in the constructor only.
➢ The blank final variable can be static also which will be initialized in the static
block only.
1) Java final variable:
➢ If you make any variable final, you cannot change the value of final variable
(It will be constant).

Example:
➢ There is a final variable speed limit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.

class Bike9
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
} } //end of class

Output:

Compile Time Error


2) Java final method:
➢ If you make any method as final, you cannot override it.

Example:
class Bike
{
final void run()
{
System.out.println("running");
} }
class Honda extends Bike
{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
} }
Output:

Compile Time Error


3) Java final class:
➢ If you make any class as final, you cannot extend it.

Example:
final class Bike
{
}
class Honda1 extends Bike
{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
} }
Output:

Compile Time Error

Is final method inherited?


➢ Yes, final method is inherited but you cannot override it.

Example:

class Bike
{
final void run(){System.out.println("running...");
}
}
class Honda2 extends Bike
{
public static void main(String args[])
{
new Honda2().run();
} }
What is a blank or uninitialized final variable?

➢ A final variable that is not initialized at the time of declaration is known


as a blank final variable.
➢ If you want to create a variable that is initialized at the time of creating an
object and once initialized may not be changed, it is useful.
➢ For example PAN CARD number of an employee.
(It can be initialized only in the constructor.)

Example:
class Student
{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}

Can we initialize blank final variable?


➢ Yes, but only in constructor.

Example:
class Bike10
{
final int speedlimit;//blank final variable
Bike10()
{
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[])
{
new Bike10();
} }
Output:

Output: 70
static blank final variable
➢ A static final variable that is not initialized at the time of declaration is known
as static blank final variable. It can be initialized only in static block.
Example:
class A
{
static final int data;//static blank final variable
static
{
data=50;
}
public static void main(String args[])
{
System.out.println(A.data);
} }

What is final parameter?


➢ If you declare any parameter as final, you cannot change the value of it.

Example:
class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[])
{
Bike11 b=new Bike11();
b.cube(5);
} }
Output:

Compile Time Error


Method Overriding:

➢ 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).
Understanding the problem without method overriding:
➢ Let's understand the problem that we may face in the program if we don't
use method overriding.
Example:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle
{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle
{
public static void main(String args[])
{
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
} }
Output:

Vehicle is running
Problem is that I have to provide a specific implementation of run() method
in subclass that is why we use method overriding.

➢ In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter
of the method are the same, and there is IS-A relationship between the classes,
so there is method overriding.

Example:
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run(){System.out.println("Vehicle is running");
} }
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");
}

public static void main(String args[])


{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
} }

Output:

Bike is running safely


A real example of Java Method Overriding:
Consider a scenario where Bank is a class that provides functionality to get the
rate of interest. However, the rate of interest varies according to banks. For
example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of
interest.

//Java Program to demonstrate the real scenario of Java Method Overriding


//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank
{
int getRateOfInterest()
{
return 0;
} }
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{ return 8; } }
class ICICI extends Bank
{
int getRateOfInterest()
{ return 7; } }
class AXIS extends Bank
{
int getRateOfInterest()
{ return 9; } }
//Test class to create objects and call the methods
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
} }

Output:

SBI Rate of Interest: 8


ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?


➢ No, a static method cannot be overridden. It can be proved by runtime polymorphism, so
we will learn it later.

Can we override java main method?


➢ No, because the main is a static method.

Difference between method overloading and method overriding:


No. Method Overloading Method Overriding

Method overriding is used to provide the


Method overloading is used to
specific implementation of the method
1) increase the readability of the
that is already provided by its super
program.
class.

Method overriding occurs in two


Method overloading is
2) classes that have IS-A (inheritance)
performed within class.
relationship.

In case of method
In case of method overriding, parameter
3) overloading, parameter must be
must be same.
different.

Method overloading is the example Method overriding is the example of run


4)
of compile time polymorphism. time polymorphism.

In java, method overloading can't be


performed by changing return type of
the method only. Return type can be Return type must be same or covariant in
5)
same or different in method method overriding.
overloading. But you must have to
change the parameter.
Example: Method Overloading
class OverloadingExample
{
static int add(int a,int b)
{ return a+b; }
static int add(int a,int b,int c)
{ return a+b+c; }
}

Example: Method Overriding


class Animal
{
void eat()
{
System.out.println("eating...");
} }
class Dog extends Animal
{
void eat(){System.out.println("eating bread...");
} }
Inner classes
Inner Classes (Nested Classes):

 Java inner class or nested class is a class that is declared inside


the class or interface.
 We use inner classes to logically group classes and interfaces in one
place to be more readable and maintainable.
 Additionally, it can access all the members of the outer class,
including private data members and methods.

Syntax of Inner class


class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
} }
Example:
class OuterClass
{
int x = 10;
class InnerClass
{
int y = 5;
}}
public class Main
{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}}
Outputs:
15 (5 + 10)
Advantages of Java inner classes:
There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it


can access all the members (data members and methods) of
the outer class, including private.
2. Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3. Code Optimization: It requires less code to write.

Need of Java Inner class:


 Sometimes users need to program a class in such a way so that no
other class can access it. Therefore, it would be better if you include it
within other classes.
 If all the class objects are a part of the outer object then it is easier to
nest that class inside the outer class. That way all the outer class can
access all the objects of the inner class.

Types of Nested classes


 There are two types of nested classes non-static and static nested
classes. The non-static nested classes are also known as inner
classes.

 Non-static nested class (inner class)

 Member inner class


 Anonymous inner class
 Local inner class

 Static nested class

Type Description

Member Inner Class A class created within class and outside method.

A class created for implementing an interface or


Anonymous Inner Class
extending class. The java compiler decides its name.
Local Inner Class A class was created within the method.

Static Nested Class A static class was created within the class.

Nested Interface An interface created within class or interface.


Exception Handling- Exception Hierarchy - Exception Types
Exception Handling:
➢ Java Exception Handling is a mechanism to handle runtime errors
such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
What are Java Exceptions?
➢ In Java, an Exception is an unwanted or unexpected event, that occurs
during the execution of a program, i.e. at run time, that disrupts the
normal flow of the program’s instructions.
➢ Exceptions can be caught and handled by the program.
➢ When an exception occurs within a method, it creates an object. This
object is called the exception object.
Major reasons why an exception Occurs:
➢ Invalid user input
➢ Code errors
➢ Out of bound
➢ Null reference
➢ Type mismatch
➢ Arithmetic errors

Difference between Error and Exception:


Error: An Error indicates a serious problem that an application should
not try to catch or handle.
Exception: Exception indicates conditions that a reasonable application
might try to catch. i.e. conditions that a program or application can
anticipate and recover from during execution.
Exception Hierarchy:
➢ All exception and error types are subclasses of the class Throwable,
which is the base class of the hierarchy.
➢ One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. NullPointerException is an
example of such an exception.
➢ Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
Java Exception Keywords:
➢ Java provides five keywords that are used to handle the exception.

Keyword Description

• The "try" keyword is used to specify a block where we should


place an exception code.
try
• It means we can't use try block alone.
• The try block must be followed by either a catch or finally.

• The "catch" block is used to handle the exception.


• It must be preceded by try block which means we can't use
catch
catch block alone.
• It can be followed by finally block later.

• The "finally" block is used to execute the necessary code of


finally the program.
• It is executed whether an exception is handled or not.

• The "throw" keyword is used to throw an exception.


• Used to explicitly throw an exception from a method or block of
throw code.
• Usage: You can throw both checked and unchecked
exceptions using throw.

• The "throws" keyword is used to declare exceptions.


• It specifies that there may be an exception in the method.
• Used in a method declaration to indicate that the method may
throw one or more exceptions.
• It doesn't throw an exception. It is always used with method
throws
signature.
• It informs callers of the method that they need to handle these
exceptions.
• Can only be used with checked exceptions (those that are
not subclasses of RuntimeException)
Types of Exceptions:

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

try-catch Syntax:
try
{
// Code that may throw an exception
} catch (ExceptionType e)
{
// Code to handle the exception
}
throw Syntax:

throw new ExceptionType("Error message")


1. Built-in Exceptions:
➢ Built-in exceptions are the exceptions that are available in Java
libraries.
➢ These exceptions are suitable to explain certain error situations.
• Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by
the compiler.
• Unchecked Exceptions: The compiler will not check these
exceptions at compile time.

➢ Below is the list of important built-in exceptions in Java:

1. ArithmeticException: It is thrown when an exceptional condition has


occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an
array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to
access a class whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not
accessible or does not open.
5. IOException: It is thrown when an input-output operation failed or
interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping,
or doing some processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain
the field (or variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that
is not found.
9. NullPointerException: This exception is raised when referring to the
members of a null object. Null represents nothing
10. NumberFormatException: This exception is raised when a method
could not convert a string into a numeric format.
11. RuntimeException: This represents an exception that occurs during
runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class
methods to indicate that an index is either negative or greater than the
size of the string
13. IllegalArgumentException : This exception will throw the error or
error statement when the method receives an argument which is not
accurately fit to the given relation or condition. It comes under the
unchecked exception.
14. IllegalStateException : This exception will throw an error or error
message when the method is not accessed for the particular operation
in the application. It comes under the unchecked exception .
Examples:
1. Arithmetic exception:
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
2. NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
3. StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
2. User-Defined Exceptions:
➢ Sometimes, the built-in exceptions in Java are not able to describe a
certain situation.
➢ In such cases, the user can also create exceptions which are called
‘user-defined Exceptions’.

The following steps are followed for the creation of a user-defined

➢ The user should create an exception class as a subclass of the


Exception class. Since all the exceptions are subclasses of the
Exception class, the user should also make his class a subclass of it.
This is done as:
class MyException extends Exception

➢ We can write a default constructor in his own exception class.


MyException(){}

➢ We can also create a parameterized constructor with a string as a


parameter.
➢ We can use this to store exception details. We can call the
superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
➢ To raise an exception of a user-defined type, we need to create an
object to his exception class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);

throw me;
➢ In main() method, the details are displayed using a for-loop.
➢ At this time, a check is done if in any account the balance amount is less
than the minimum balance amount in the account.
➢ If it is so, then MyException is raised and a message is displayed “Balance
amount is less”.
Example:

/* Java program to demonstrate user-defined exception. This program


throws an exception whenever the balance amount is below Rs 1000 */
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};
private static String name[] =
{"Nish", "Shubh", "Sush", "Abhi", "Akash"};
private static double bal[] =
{10000.00, 12000.00, 5600.0, 999.00, 1100.55};

// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" + "\t" +
"BALANCE");
// display the actual account information
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] + "\t" + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
} } } //end of try
catch (MyException e)
{
e.printStackTrace();
} } }

Runtime Error:
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)

Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0

The advantages of Exception Handling:


1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Meaningful Error Reporting
4. Identifying Error Types
public class UserDefinedExceptionExample {
static void checkAge(int age) throws AgeNotValidException {
if (age < 18) {
throw new AgeNotValidException("Age must be 18 or older.");
}
System.out.println("Access granted. Age: " + age);
}

public static void main(String[] args) {


try {
checkAge(15); // This will throw the custom exception
} catch (AgeNotValidException e) {
// Handle the exception
System.out.println("Caught an exception: " + e.getMessage());
}

try {
checkAge(20); // This will not throw an exception
} catch (AgeNotValidException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
Example Using All Keywords:
import java.io.*;
public class ExceptionHandlingExample
{
// Method that declares it throws an exception
public static void readFile() throws IOException
{
FileReader file = new FileReader("test.txt");
BufferedReader fileInput = new BufferedReader(file);

// This will throw IOException


throw new IOException("File not found");
}
public static void main(String[] args)
{
try
{
readFile(); // Might throw IOException
}
catch (IOException e)
{
System.out.println("An exception occurred: " + e);
}
finally
{
System.out.println("Finally block always executes.");
}
}
}
Collection Class - Collections Framework
Collection Class:

➢ Java collection class is used exclusively with static methods that


operate on or return collections. It inherits Object class.
The important points about Java Collections class are:
o Java Collection class supports the polymorphic algorithms that
operate on collections.
o Java Collection class throws a NullPointerException if the
collections or class objects provided to them are null.

Collections class declaration:


➢ The declaration for java.util.Collections class.

public class Collections extends Object

SN Modifier & Type Methods Descriptions

It is used to adds all of the specified


1) static <T> boolean addAll()
elements to the specified collection.

It returns a view of a Deque as a


2) static <T> Queue<T> asLifoQueue()
Last-in-first-out (LIFO) Queue.

It searches the list for the specified


3) static <T> int binarySearch() object and returns their position in a
sorted list.

It is used to returns a dynamically


4) static <E> Collection<E> checkedCollection() typesafe view of the specified
collection.

It is used to returns a dynamically


5) static <E> List<E> checkedList()
typesafe view of the specified list.

It is used to returns a dynamically


6) static <K,V> Map<K,V> checkedMap()
typesafe view of the specified map.

It is used to returns a dynamically


static <K,V> checkedNavigableMa
7) typesafe view of the specified
NavigableMap<K,V> p()
navigable map.
It is used to returns a dynamically
static <E> checkedNavigableSe
8) typesafe view of the specified
NavigableSet<E> t()
navigable set.

It is used to returns a dynamically


9) static <E> Queue<E> checkedQueue() typesafe view of the specified
queue.

It is used to returns a dynamically


10) static <E> Set<E> checkedSet()
typesafe view of the specified set.

It is used to returns a dynamically


static <K,V>
11) checkedSortedMap() typesafe view of the specified sorted
SortedMap<K,V>
map.

It is used to returns a dynamically


12) static <E> SortedSet<E> checkedSortedSet() typesafe view of the specified sorted
set.

It is used to copy all the elements


13) static <T> void copy()
from one list into another list.

It returns true if the two specified


14) static boolean disjoint() collections have no elements in
common.

static <T> It is used to get an enumeration that


15) emptyEnumeration()
Enumeration<T> has no elements.

It is used to get an Iterator that has


16) static <T> Iterator<T> emptyIterator()
no elements.

It is used to get a List that has no


17) static <T> List<T> emptyList()
elements.

It is used to get a List Iterator that


18) static <T> ListIterator<T> emptyListIterator()
has no elements.

It returns an empty map which is


19) static <K,V> Map<K,V> emptyMap()
immutable.

static <K,V> emptyNavigableMap( It returns an empty navigable map


20)
NavigableMap<K,V> ) which is immutable.

static <E> It is used to get an empty navigable


21) emptyNavigableSet()
NavigableSet<E> set which is immutable in nature.

It is used to get the set that has no


22) static <T> Set<T> emptySet()
elements.

static <K,V> It returns an empty sorted map


23) emptySortedMap()
SortedMap<K,V> which is immutable.
It is used to get the sorted set that
24) static <E> SortedSet<E> emptySortedSet()
has no elements.

static <T> It is used to get the enumeration


25) enumeration()
Enumeration<T> over the specified collection.

It is used to replace all of the


26) static <T> void fill() elements of the specified list with
the specified elements.

It is used to get the number of


27) static int frequency() elements in the specified collection
equal to the specified object.

It is used to get the starting position


of the first occurrence of the
specified target list within the
28) static int indexOfSubList()
specified source list. It returns -1 if
there is no such occurrence in the
specified list.

It is used to get the starting position


of the last occurrence of the
specified target list within the
29) static int lastIndexOfSubList()
specified source list. It returns -1 if
there is no such occurrence in the
specified list.

It is used to get an array list


containing the elements returned by
30) static <T> ArrayList<T> list() the specified enumeration in the
order in which they are returned by
the enumeration.

static <T extends Object & It is used to get the maximum value
31) Comparable<? super T>> max() of the given collection, according to
T the natural ordering of its elements.

static <T extends Object & It is used to get the minimum value
32) Comparable<? super T>> min() of the given collection, according to
T the natural ordering of its elements.

It is used to get an immutable list


33) static <T> List<T> nCopies() consisting of n copies of the
specified object.

It is used to return a set backed by


34) static <E> Set<E> newSetFromMap()
the specified map.

It is used to replace all occurrences


35) static <T> boolean replaceAll() of one specified value in a list with
the other specified value.
It is used to reverse the order of the
36) static void reverse()
elements in the specified list.

It is used to get the comparator that


imposes the reverse of the natural
37) static <T> Comparator<T> reverseOrder() ordering on a collection of objects
which implement the Comparable
interface.

It is used to rotate the elements in


38) static void rotate() the specified list by a given
distance.

It is used to randomly reorders the


39) static void shuffle() specified list elements using a
default randomness.

It is used to get an immutable set


40) static <T> Set<T> singleton() which contains only the specified
object.

It is used to get an immutable list


41) static <T> List<T> singletonList() which contains only the specified
object.

It is used to get an immutable map,


42) static <K,V> Map<K,V> singletonMap() mapping only the specified key to
the specified value.

static <T extends It is used to sort the elements


43) Comparable<? super sort() presents in the specified list of
T>>void collection in ascending order.

It is used to swap the elements at


44) static void swap() the specified positions in the
specified list.

It is used to get a synchronized


synchronizedCollecti
45) static <T> Collection<T> (thread-safe) collection backed by
on()
the specified collection.

It is used to get a synchronized


46) static <T> List<T> synchronizedList() (thread-safe) collection backed by
the specified list.

It is used to get a synchronized


47) static <K,V> Map<K,V> synchronizedMap() (thread-safe) map backed by the
specified map.

It is used to get a synchronized


static <K,V> synchronizedNavigab
48) (thread-safe) navigable map backed
NavigableMap<K,V> leMap()
by the specified navigable map.
It is used to get a synchronized
static <T> synchronizedNavigab
49) (thread-safe) navigable set backed
NavigableSet<T> leSet()
by the specified navigable set.

It is used to get a synchronized


50) static <T> Set<T> synchronizedSet() (thread-safe) set backed by the
specified set.

It is used to get a synchronized


static <K,V> synchronizedSorted
51) (thread-safe) sorted map backed by
SortedMap<K,V> Map()
the specified sorted map.

It is used to get a synchronized


synchronizedSortedS
52) static <T> SortedSet<T> (thread-safe) sorted set backed by
et()
the specified sorted set.

unmodifiableCollectio It is used to get an unmodifiable


53) static <T> Collection<T>
n() view of the specified collection.

It is used to get an unmodifiable


54) static <T> List<T> unmodifiableList()
view of the specified list.

It is used to get an unmodifiable


55) static <K,V> Map<K,V> unmodifiableMap()
view of the specified map.

static <K,V> unmodifiableNavigabl It is used to get an unmodifiable


56)
NavigableMap<K,V> eMap() view of the specified navigable map.

static <T> unmodifiableNavigabl It is used to get an unmodifiable


57)
NavigableSet<T> eSet() view of the specified navigable set.

It is used to get an unmodifiable


58) static <T> Set<T> unmodifiableSet()
view of the specified set.

static <K,V> unmodifiableSortedM It is used to get an unmodifiable


59)
SortedMap<K,V> ap() view of the specified sorted map.

unmodifiableSortedS It is used to get an unmodifiable


60 static <T> SortedSet<T>
et() view of the specified sorted set.
Java Collections Example

import java.util.*;
public class CollectionsExample
{
public static void main(String a[])
{
List<String> list = new ArrayList<String>();
list.add("C");
list.add("Core Java");
list.add("Advance Java");
System.out.println("Initial collection value:"+list);
Collections.addAll(list, "Servlet","JSP");
System.out.println("After adding elements collection value:"+list);
String[] strArr = {"C#", ".Net"};
Collections.addAll(list, strArr);
System.out.println("After adding array collection value:"+list);
}
}
Output:

Initial collection value: [C, Core Java, Advance Java]


After adding elements collection value: [C, Core Java, Advance Java, Servlet, JSP]
After adding array collection value: [C, Core Java, Advance Java, Servlet, JSP, C#, .Net]
Java Collections Example: max()

import java.util.*;
public class CollectionsExample
{
public static void main(String a[])
{
List<Integer> list = new ArrayList<Integer>();
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
System.out.println("Value of maximum element from the collection:
"+Collections.max(list));
}
}
Output:

Value of maximum element from the collection: 67


Collections Framework:

➢ The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.
➢ Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
➢ Java Collection means a single unit of objects.
➢ Java Collection framework provides many interfaces (Set, List, Queue,
Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).

What is Collection:
➢ A Collection represents a single unit of objects, i.e., a group.

What is a framework:
➢ It provides readymade architecture.
➢ It represents a set of classes and interfaces.
➢ It is optional.

What is Collection framework:


➢ The Collection framework represents a unified architecture for
storing and manipulating a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Hierarchy of Collection Framework:
➢ The java.util package contains all the classes and interfaces for the
Collection framework.
Methods of Collection interface:
➢ There are many methods declared in the Collection interface. They
are as follows:

No. Method Description

It is used to insert an element in this


1 public boolean add(E e)
collection.

public boolean addAll(Collection<? It is used to insert the specified collection


2
extends E> c) elements in the invoking collection.

It is used to delete an element from the


3 public boolean remove(Object element)
collection.

It is used to delete all the elements of the


public boolean removeAll(Collection<?>
4 specified collection from the invoking
c)
collection.

It is used to delete all the elements of the


default boolean removeIf(Predicate<?
5 collection that satisfy the specified
super E> filter)
predicate.

It is used to delete all the elements of


public boolean retainAll(Collection<?>
6 invoking collection except the specified
c)
collection.

It returns the total number of elements in the


7 public int size()
collection.

It removes the total number of elements


8 public void clear()
from the collection.

public boolean contains(Object


9 It is used to search an element.
element)

public boolean It is used to search the specified collection


10
containsAll(Collection<?> c) in the collection.
11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

It converts collection into array. Here, the


13 public <T> T[] toArray(T[] a) runtime type of the returned array is that of
the specified array.

14 public boolean isEmpty() It checks if collection is empty.

It returns a possibly parallel Stream with the


15 default Stream<E> parallelStream()
collection as its source.

It returns a sequential Stream with the


16 default Stream<E> stream()
collection as its source.

It generates a Spliterator over the specified


17 default Spliterator<E> spliterator()
elements in the collection.

18 public boolean equals(Object element) It matches two collections.

It returns the hash code number of the


19 public int hashCode()
collection.
Iterator interface:
➢ Iterator interface provides the facility of iterating the elements in a
forward direction only.

Methods of Iterator interface:


There are only three methods in the Iterator interface. They are:

No. Method Description

It returns true if the iterator has more elements


1 public boolean hasNext()
otherwise it returns false.

It returns the element and moves the cursor pointer to


2 public Object next()
the next element.

It removes the last elements returned by the iterator. It


3 public void remove()
is less used.
Interface & Classes Implementation: Set- List- Queue-Map
Class:
➢ A class is a user-defined blueprint or prototype from which objects
are created.
➢ It represents the set of properties or methods that are common to all
objects of one type.
Interface:
➢ Like a class, an interface can have methods and variables, but the
methods declared in an interface are by default abstract (only method
signature, nobody).
➢ Interfaces specify what a class must do and not how. It is the blueprint
of the class.
(1). List Interface:
➢ List interface is the child interface of Collection interface. It inhibits
a list type data structure in which we can store the ordered collection of
objects. It can have duplicate values.
➢ List interface is implemented by the classes ArrayList, LinkedList,
Vector, and Stack.

To instantiate the List interface, we must use :


List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

➢ There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
i). ArrayList:

➢ The ArrayList class implements the List interface. It uses a dynamic


array to store the duplicate element of different data types.
➢ The ArrayList class maintains the insertion order and is non-
synchronized.
➢ The elements stored in the ArrayList class can be randomly accessed.
Consider the following example:

import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ravi
Vijay
Ravi
Ajay
ii) LinkedList:

➢ LinkedList implements the Collection interface. It uses a doubly linked


list internally to store the elements. It can store the duplicate
elements.
➢ It maintains the insertion order and is not synchronized. In LinkedList,
the manipulation is fast because no shifting is required.

Consider the following example:


import java.util.*;
public class TestJavaCollection2
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ravi
Vijay
Ravi
Ajay
iii). Vector:

➢ Vector uses a dynamic array to store the data elements. It is similar


to ArrayList.
➢ However, It is synchronized and contains many methods that are
not the part of Collection framework.

Consider the following example:

import java.util.*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ayush
Amit
Ashish
Garima
iv). Stack:

➢ The stack is the subclass of Vector.


➢ It implements the last-in-first-out data structure, i.e., Stack.
➢ The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o),
which defines its properties.
Consider the following example:
import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
} }}
Output:

Ayush
Garvit
Amit
Ashish
(2). Queue Interface:

➢ Queue interface maintains the first-in-first-out order. It can be defined


as an ordered list that is used to hold the elements which are about to be
processed.
➢ There are various classes like PriorityQueue, Deque, and
ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:


Queue<String> q1 = new PriorityQueue();
Queue<String> q2 = new ArrayDeque();
(i). PriorityQueue:

➢ The PriorityQueue class implements the Queue interface.


➢ It holds the elements or objects which are to be processed by their
priorities.
➢ PriorityQueue doesn't allow null values to be stored in the queue.
Consider the following example.

import java.util.*;
public class TestJavaCollection5
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
} } }
Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
(3). Deque Interface:

➢ Deque interface extends the Queue interface.


➢ In Deque, we can remove and add the elements from both the side.
➢ Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.
Deque can be instantiated as:

Deque d = new ArrayDeque();

(i). ArrayDeque:

➢ ArrayDeque class implements the Deque interface. It facilitates us to


use the Deque.
➢ Unlike queue, we can add or delete the elements from both the
ends.
➢ ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.

Consider the following example:


import java.util.*;
public class TestJavaCollection6
{
public static void main(String[] args)
{
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque)
{
System.out.println(str);
} } }
Output:

Gautam
Karan
Ajay

(4). Set Interface:

➢ Set Interface in Java is present in java.util package.


➢ It extends the Collection interface. It represents the unordered set of
elements which doesn't allow us to store the duplicate items.
➢ We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();


Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
(i). HashSet:

➢ HashSet class implements Set Interface. It represents the collection


that uses a hash table for storage.
➢ Hashing is used to store the elements in the HashSet. It contains
unique items.

Consider the following example.

mport java.util.*;
public class TestJavaCollection7
{
public static void main(String args[])
{
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

Output:

Vijay
Ravi
Ajay
(ii). LinkedHashSet:

➢ LinkedHashSet class represents the LinkedList implementation of Set


Interface.
➢ It extends the HashSet class and implements Set interface. Like
HashSet, It also contains unique elements.
➢ It maintains the insertion order and permits null elements.

Consider the following example:


import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ravi
Vijay
Ajay
(5). SortedSet Interface:

➢ SortedSet is the alternate of Set interface that provides a total ordering


on its elements.
➢ The elements of the SortedSet are arranged in the increasing
(ascending) order.
➢ The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.

The SortedSet can be instantiated as:

SortedSet<data-type> set = new TreeSet();

(i). TreeSet:

➢ Java TreeSet class implements the Set interface that uses a tree for
storage.
➢ Like HashSet, TreeSet also contains unique elements.
➢ However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

Consider the following example:

import java.util.*;
public class TestJavaCollection9
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ajay
Ravi
Vijay

(6). Map Interface:


➢ A map is a data structure that supports the key-value pair for
mapping the data.
➢ This interface doesn’t support duplicate keys because the same key
cannot have multiple mappings, however, it allows duplicate values
in different keys.
➢ A map is useful if there is data and we wish to perform operations on
the basis of the key.
➢ This map interface is implemented by various classes
like HashMap, TreeMap, etc. Since all the subclasses implement the
map, we can instantiate a map object with any of these classes.

For example:
Map<T> hm = new HashMap<> ();
Map<T> tm = new TreeMap<> ();

Where T is the type of the object.

The frequently used implementation of a Map interface is a


HashMap.
➢ HashMap provides the basic implementation of the Map interface of
Java. It stores the data in (Key, Value) pairs.
➢ To access a value in a HashMap, we must know its key. HashMap
uses a technique called Hashing.
➢ Hashing is a technique of converting a large String to a small
String that represents the same String so that the indexing and
search operations are faster.
➢ HashSet also uses HashMap internally.

Let’s understand the HashMap with an example:


// Java program to demonstrate the
// working of a HashMap
import java.util.*;
public class HashMapDemo
{
// Main Method
public static void main(String args[])
{
// Creating HashMap and
// adding elements
HashMap<Integer, String> hm
= new HashMap<Integer, String>();
hm.put(1, "Geeks");
hm.put(2, "For");
hm.put(3, "Geeks");
// Finding the value for a key
System.out.println("Value for 1 is " + hm.get(1));
// Traversing through the HashMap
for (Map.Entry<Integer, String> e : hm.entrySet())
System.out.println(e.getKey() + " "
+ e.getValue());
} }

Output:

Value for 1 is Geeks


1 Geeks
2 For
3 Geeks
Interface & Classes Implementation: Set- List- Queue-Map
Class:
➢ A class is a user-defined blueprint or prototype from which objects
are created.
➢ It represents the set of properties or methods that are common to all
objects of one type.
Interface:
➢ Like a class, an interface can have methods and variables, but the
methods declared in an interface are by default abstract (only method
signature, nobody).
➢ Interfaces specify what a class must do and not how. It is the blueprint
of the class.
(1). List Interface:
➢ List interface is the child interface of Collection interface. It inhibits
a list type data structure in which we can store the ordered collection of
objects. It can have duplicate values.
➢ List interface is implemented by the classes ArrayList, LinkedList,
Vector, and Stack.

To instantiate the List interface, we must use :


List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

➢ There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
i). ArrayList:

➢ The ArrayList class implements the List interface. It uses a dynamic


array to store the duplicate element of different data types.
➢ The ArrayList class maintains the insertion order and is non-
synchronized.
➢ The elements stored in the ArrayList class can be randomly accessed.
Consider the following example:

import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ravi
Vijay
Ravi
Ajay
ii) LinkedList:

➢ LinkedList implements the Collection interface. It uses a doubly linked


list internally to store the elements. It can store the duplicate
elements.
➢ It maintains the insertion order and is not synchronized. In LinkedList,
the manipulation is fast because no shifting is required.

Consider the following example:


import java.util.*;
public class TestJavaCollection2
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ravi
Vijay
Ravi
Ajay
iii). Vector:

➢ Vector uses a dynamic array to store the data elements. It is similar


to ArrayList.
➢ However, It is synchronized and contains many methods that are
not the part of Collection framework.

Consider the following example:

import java.util.*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ayush
Amit
Ashish
Garima
iv). Stack:

➢ The stack is the subclass of Vector.


➢ It implements the last-in-first-out data structure, i.e., Stack.
➢ The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o),
which defines its properties.
Consider the following example:
import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
} }}
Output:

Ayush
Garvit
Amit
Ashish
(2). Queue Interface:

➢ Queue interface maintains the first-in-first-out order. It can be defined


as an ordered list that is used to hold the elements which are about to be
processed.
➢ There are various classes like PriorityQueue, Deque, and
ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:


Queue<String> q1 = new PriorityQueue();
Queue<String> q2 = new ArrayDeque();
(i). PriorityQueue:

➢ The PriorityQueue class implements the Queue interface.


➢ It holds the elements or objects which are to be processed by their
priorities.
➢ PriorityQueue doesn't allow null values to be stored in the queue.
Consider the following example.

import java.util.*;
public class TestJavaCollection5
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
} } }
Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

(3). Deque Interface:


➢ Deque interface extends the Queue interface.
➢ In Deque, we can remove and add the elements from both the side.
➢ Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.
Deque can be instantiated as:

Deque d = new ArrayDeque();

(i). ArrayDeque:

➢ ArrayDeque class implements the Deque interface. It facilitates us to


use the Deque.
➢ Unlike queue, we can add or delete the elements from both the
ends.
➢ ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.

Consider the following example:


import java.util.*;
public class TestJavaCollection6
{
public static void main(String[] args)
{
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque)
{
System.out.println(str);
} } }

Output:

Gautam
Karan
Ajay

(4). Set Interface:

➢ Set Interface in Java is present in java.util package.


➢ It extends the Collection interface. It represents the unordered set of
elements which doesn't allow us to store the duplicate items.
➢ We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();


Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
(i). HashSet:

➢ HashSet class implements Set Interface. It represents the collection


that uses a hash table for storage.
➢ Hashing is used to store the elements in the HashSet. It contains
unique items.

Consider the following example.

mport java.util.*;
public class TestJavaCollection7
{
public static void main(String args[])
{
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

Output:

Vijay
Ravi
Ajay
(ii). LinkedHashSet:

➢ LinkedHashSet class represents the LinkedList implementation of Set


Interface.
➢ It extends the HashSet class and implements Set interface. Like
HashSet, It also contains unique elements.
➢ It maintains the insertion order and permits null elements.

Consider the following example:


import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ravi
Vijay
Ajay
(5). SortedSet Interface:

➢ SortedSet is the alternate of Set interface that provides a total ordering


on its elements.
➢ The elements of the SortedSet are arranged in the increasing
(ascending) order.
➢ The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.

The SortedSet can be instantiated as:

SortedSet<data-type> set = new TreeSet();

(i). TreeSet:

➢ Java TreeSet class implements the Set interface that uses a tree for
storage.
➢ Like HashSet, TreeSet also contains unique elements.
➢ However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

Consider the following example:

import java.util.*;
public class TestJavaCollection9
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:

Ajay
Ravi
Vijay

(6). Map Interface:


➢ A map is a data structure that supports the key-value pair for
mapping the data.
➢ This interface doesn’t support duplicate keys because the same key
cannot have multiple mappings, however, it allows duplicate values
in different keys.
➢ A map is useful if there is data and we wish to perform operations on
the basis of the key.
➢ This map interface is implemented by various classes
like HashMap, TreeMap, etc. Since all the subclasses implement the
map, we can instantiate a map object with any of these classes.

For example:
Map<T> hm = new HashMap<> ();
Map<T> tm = new TreeMap<> ();

Where T is the type of the object.

The frequently used implementation of a Map interface is a


HashMap.
➢ HashMap provides the basic implementation of the Map interface of
Java. It stores the data in (Key, Value) pairs.
➢ To access a value in a HashMap, we must know its key. HashMap
uses a technique called Hashing.
➢ Hashing is a technique of converting a large String to a small
String that represents the same String so that the indexing and
search operations are faster.
➢ HashSet also uses HashMap internally.

Let’s understand the HashMap with an example:


// Java program to demonstrate the
// working of a HashMap
import java.util.*;
public class HashMapDemo
{
// Main Method
public static void main(String args[])
{
// Creating HashMap and
// adding elements
HashMap<Integer, String> hm
= new HashMap<Integer, String>();
hm.put(1, "Geeks");
hm.put(2, "For");
hm.put(3, "Geeks");
// Finding the value for a key
System.out.println("Value for 1 is " + hm.get(1));
// Traversing through the HashMap
for (Map.Entry<Integer, String> e : hm.entrySet())
System.out.println(e.getKey() + " "
+ e.getValue());
} }

Output:

Value for 1 is Geeks


1 Geeks
2 For
3 Geeks
File- IO Stream- Character Streams – Byte Streams

Java I/O:

➢ 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.

Stream:

➢ A stream is a sequence of data. In Java, a stream is composed of bytes.


➢ 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

OutputStream vs InputStream:

OutputStream
➢ Java application uses an output stream to write data to a destination; it
may be a file, an array, peripheral device or socket.

InputStream
➢ Java application uses an input stream to read data from a source; it may
be a file, an array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the
figure given below.

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.

Useful methods of OutputStream:


Method Description

is used to write a byte to the


1) public void write(int)throws IOException
current output stream.

is used to write an array of byte to


2) public void write(byte[])throws IOException
the current output stream.

3) public void flush()throws IOException flushes the current output stream.

is used to close the current output


4) public void close()throws IOException
stream.
OutputStream Hierarchy:

InputStream class:
➢ InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.

Useful methods of InputStream

Method Description

reads the next byte of data from the input stream.


1) public abstract int read()throws IOException
It returns -1 at the end of the file.

returns an estimate of the number of bytes that


2) public int available()throws IOException
can be read from the current input stream.

3) public void close()throws IOException is used to close the current input stream.

InputStream Hierarchy:
Character Streams:
➢ The java.io package provides CharacterStream classes to overcome
the limitations of ByteStream classes, which can only handle the 8-bit
bytes and is not compatible to work directly with the Unicode characters.
➢ CharacterStream classes are used to work with 16-bit Unicode
characters.
➢ They can perform operations on characters, char arrays and
Strings.
➢ However, the CharacterStream classes are mainly used to read
characters from the source and write them to the destination.
➢ The CharacterStream classes are divided into two types of classes,
1. Reader class and 2. Writer class.

1. Reader Class:
➢ Reader class is used to read the 16-bit characters from the input
stream.
➢ However, it is an abstract class and can't be instantiated, but various
subclasses inherit the Reader class and override the methods of the
Reader class.
➢ All methods of the Reader class throw an IOException. The subclasses
of the Reader class are given in the following table.

SN Class Description

1. BufferedReader This class provides methods to read characters from the buffer.

This class provides methods to read characters from the char


2. CharArrayReader
array.

3. FileReader This class provides methods to read characters from the file.
This class provides methods to read characters from the
4. FilterReader
underlying character input stream.

5 InputStreamReader This class provides methods to convert bytes to characters.

This class provides methods to read characters from the


6 PipedReader
connected piped output stream.

7 StringReader This class provides methods to read characters from a string.

➢ The Reader class methods are given in the following table.

SN Method Description

This method returns the integral representation of the next


1 int read() character present in the input. It returns -1 if the end of the input
is encountered.

This method is used to read from the specified buffer. It returns


2 int read(char buffer[]) the total number of characters successfully read. It returns -1 if
the end of the input is encountered.

This method is used to read the specified nChars from the buffer
int read(char buffer[],
3 at the specified location. It returns the total number of characters
int loc, int nChars)
successfully read.

This method is used to mark the current position in the input


4 void mark(int nchars)
stream until nChars characters are read.

This method is used to reset the input pointer to the previous set
5 void reset()
mark.

long skip(long This method is used to skip the specified nChars characters from
6
nChars) the input stream and returns the number of characters skipped.

This method returns a boolean value true if the next request of


7 boolean ready()
input is ready. Otherwise, it returns false.
This method is used to close the input stream. However, if the
8 void close()
program attempts to access the input, it generates IOException.

2. Writer Class:
➢ Writer class is used to write 16-bit Unicode characters to the output
stream. The methods of the Writer class generate IOException.
➢ Like Reader class, Writer class is also an abstract class that cannot be
instantiated; therefore, the subclasses of the Writer class are used to
write the characters onto the output stream.
➢ The subclasses of the Writer class are given in the below table.

SN Class Description

1 BufferedWriter This class provides methods to write characters to the buffer.

2 FileWriter This class provides methods to write characters to the file.

This class provides methods to write the characters to the


3 CharArrayWriter
character array.

4 OutpuStreamWriter This class provides methods to convert from bytes to characters.

This class provides methods to write the characters to the piped


5 PipedWriter
output stream.

6 StringWriter This class provides methods to write the characters to the string.

➢ To write the characters to the output stream, the Write class provides
various methods given in the following table.
SN Method Description

This method is used to write the data to the output


1 void write()
stream.

This method is used to write a single character to


2 void write(int i)
the output stream.

This method is used to write the array of characters


3 Void write(char buffer[])
to the output stream.

void write(char buffer [],int This method is used to write the nChars characters
4
loc, int nChars) to the character array from the specified location.

This method is used to close the output stream.


However, this generates the IOException if an
5 void close ()
attempt is made to write to the output stream after
closing the stream.

This method is used to flush the output stream


6 void flush ()
and writes the waiting buffered characters.

Byte Streams:
➢ ByteStream classes are used to read bytes from the input stream
and write bytes to the output stream.
➢ In other words, we can say that ByteStream classes read/write the
data of 8-bits.
➢ We can store video, audio, characters, etc., by using ByteStream
classes. These classes are part of the java.io package.
➢ The ByteStream classes are divided into two types of classes,
1. InputStream and 2. OutputStream.
➢ These classes are abstract and super classes of all the Input/Output
stream classes.
1. InputStream Class:
➢ The InputStream class provides methods to read bytes from a file,
console or memory.
➢ It is an abstract class and can't be instantiated; however, various
classes inherit the InputStream class and override its methods.
➢ The subclasses of InputStream class are given in the following table.

SN Class Description

This class provides methods to read bytes from the


1 BufferedInputStream
buffer.

This class provides methods to read bytes from the byte


2 ByteArrayInputStream
array.

This class provides methods to read Java primitive data


3 DataInputStream
types.

4 FileInputStream This class provides methods to read bytes from a file.

This class contains methods to read bytes from the


5 FilterInputStream other input streams, which are used as the primary
source of data.

6 ObjectInputStream This class provides methods to read objects.

This class provides methods to read from a piped output


7 PipedInputStream stream to which the piped input stream must be
connected.

This class provides methods to connect multiple Input


8 SequenceInputStream
Stream and read data from them.

➢ The InputStream class contains various methods to read the data


from an input stream.
➢ These methods are overridden by the classes that inherit the
InputStream class.

SN Method Description

This method returns an integer, an integral


representation of the next available byte of the input. The
1 int read()
integer -1 is returned once the end of the input is
encountered.

This method is used to read the specified buffer length


bytes from the input and returns the total number of
2 int read (byte buffer [])
bytes successfully read. It returns -1 once the end of the
input is encountered.

This method is used to read the 'nBytes' bytes from the


int read (byte buffer [], buffer starting at a specified location, 'loc'. It returns the
3
int loc, int nBytes) total number of bytes successfully read from the input. It
returns -1 once the end of the input is encountered.

This method returns the number of bytes that are


4 int available ()
available to read.

This method is used to mark the current position in the


5 Void mark(int nBytes)
input stream until the specified nBytes are read.

This method is used to reset the input pointer to the


6 void reset ()
previously set mark.

This method is used to skip the nBytes of the input


7 long skip (long nBytes) stream and returns the total number of bytes that are
skipped.

This method is used to close the input source. If an


8 void close () attempt is made to read even after the closing,
IOException is thrown by the method.
2. OutputStream Class:
➢ The OutputStream is an abstract class that is used to write 8-bit
bytes to the stream.
➢ It is the superclass of all the output stream classes. This class can't
be instantiated; however, it is inherited by various subclasses that are
given in the following table.

SN Class Description

This class provides methods to write the bytes to the


1 BufferedOutputStream
buffer.

This class provides methods to write bytes to the byte


2 ByteArrayOutputStream
array.

This class provides methods to write the java primitive


3 DataOutputStream
data types.

4 FileOutputStream This class provides methods to write bytes to a file.

This class provides methods to write to other output


5 FilterOutputStream
streams.

6 ObjectOutputStream This class provides methods to write objects.

It provides methods to write bytes to a piped output


7 PipedOutputStream
stream.

8 PrintStream It provides methods to print Java primitive data types.

➢ The OutputStream class provides various methods to write bytes


to the output streams. The methods are given in the following table.
S.N Method Description

This method is used to write the specified single


1 void write (int i)
byte to the output stream.

2 void write (byte buffer [] ) It is used to write a byte array to the output stream.

Void write(bytes buffer[],int It is used to write nByte bytes to the output stream
3
loc, int nBytes) from the buffer starting at the specified location.

It is used to flush the output stream and writes the


4 void flush ()
pending buffered bytes.

It is used to close the output stream. However, if


5 void close () we try to close the already closed output stream,
the IOException will be thrown by this method.
Example:
• The following example uses the ByteArrayInputStream to create an input
stream from a byte array "content".
• We use the read() method to read the content from an input stream.
• We have also used the write() method on a FileOutputStream object to write
the byte array content in the file.

Consider the following example.

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class InputOutputStreamExample {

public static void main(String[] args) throws IOException {


// Auto-generated method stub
byte content[] = "Learn new technologies".getBytes();
// ByteArrayInputStream to create an input stream from a byte array
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
inputStream.read(content); // read() method to read the content from an
// input stream
File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
// A new file MyNewFile.doc will be created on desktop
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(content); // write() method on a FileOutputStream object
// to write the byte array content in the file
} }

Output:

A new file MyNewFile.doc will be created on desktop with the content "Learn new
technologies".
Threads - Thread states -Thread priority
Threads in Java:
Definition:
A thread is a lightweight process or the smallest unit of
processing in Java. Java allows for multi-threaded programming,
meaning multiple tasks can be performed simultaneously to
optimize performance.
Creation: There are two primary ways to create a thread in Java:
1. Extending the Thread class:
➢ A class can extend Thread and override the run() method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running..."); } }
public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Start the thread
} }
2. Implementing the Runnable interface:
➢ A class implements Runnable and the run() method.

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running...");
} }
public class Test {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start(); }}
Thread States in Java:

➢ Java threads can be in one of the following five states as defined in


the Thread.State enum:

1. New: The thread is created but not yet started.


o Example: Thread t = new Thread();
2. Runnable: After the start() method is called, the thread is ready to
run and may be running or waiting for CPU time.
o Example: t.start();
3. Blocked: The thread is waiting to acquire a monitor lock to enter a
synchronized block/method.
o Example: If two threads are trying to access a synchronized
block at the same time.
4. Waiting: The thread is waiting indefinitely for another thread to
perform a particular action (e.g., join() or wait() without timeout).
o Example: Calling Object.wait().
5. Timed Waiting: The thread is waiting for another thread to
perform an action for a specified amount of time.
o Example: Thread.sleep() or Object.wait(timeout).
6. Terminated (Dead): The thread has finished executing either by
completing the run() method or by encountering an exception.
o Example: After the run() method finishes, the thread enters
the terminated state.

Thread State Diagram:

New → Runnable → Running → Blocked/Waiting/Timed Waiting → Terminated

Thread Priority in Java:

➢ Thread priority determines the order in which threads are scheduled


to run by the thread scheduler.
➢ Each thread in Java has a priority between 1 and 10, where:
• MIN_PRIORITY: 1
• NORM_PRIORITY: 5 (default priority)
• MAX_PRIORITY: 10

➢ Java’s thread scheduler generally schedules threads of higher


priority first, although this behavior can be platform-dependent.

Setting Thread Priority:

Thread t1 = new Thread();


t1.setPriority(Thread.MAX_PRIORITY); // Setting priority to 10

Note: While priority influences the thread scheduling, it doesn’t


guarantee the exact order of execution.
Thread Methods in Java:
Here are some common thread methods:
➢ start(): Begins the execution of a thread.
➢ run(): The code that will be executed by the thread.
➢ sleep(long millis): Causes the currently executing thread to sleep
for the specified number of milliseconds.
➢ yield(): Causes the currently executing thread to give up the CPU
and allow other threads to execute.
➢ join(): Causes the current thread to wait until another thread has
completed its execution.
➢ wait() and notify(): Used for inter-thread communication, often with
synchronization.

Thread operations -– Thread Synchronization – Multithreading:


Thread Operations in Java:

➢ Thread operations refer to the set of methods and actions you can
perform on Java threads.
➢ These operations allow thread management, coordination, and
communication between threads during execution.
➢ Common Thread Operations:
1. start(): Initiates a thread and calls its run() method.
Thread t = new Thread();
t.start(); // Starts the thread

2. run(): The main logic of the thread is placed here. This method is called
automatically when a thread is started, but it can also be called directly
(though it won’t start the thread separately).

public void run()


{
System.out.println("Thread is running...");
}

3. sleep(long millis): Pauses the current thread for a specified number of


milliseconds.

try {
Thread.sleep(1000); // Pauses for 1 second
}
catch (InterruptedException e)
{
e.printStackTrace();
}

4. join(): Causes the current thread to wait for the completion of another
thread. This is used when you want to ensure a thread finishes before
proceeding further.

t.join(); // Waits for thread t to complete


5. yield(): Temporarily pauses the current thread to allow other threads of
equal priority to execute.
Thread.yield();

6. interrupt(): Interrupts a thread, signaling it to stop its current work.


However, interruption is cooperative — the thread needs to handle the
interruption signal.

t.interrupt(); // Sends interrupt signal to thread t

Thread Synchronization in Java:

➢ Synchronization is essential in multi-threaded environments where


multiple threads may concurrently access shared resources. Without
synchronization, data inconsistency and thread interference can occur.

Why Synchronization is Important:

• Thread Interference: Occurs when multiple threads access and


modify shared data simultaneously, leading to unpredictable
outcomes.
• Race Conditions: Multiple threads may "race" to access shared
resources, and depending on which thread accesses the resource
first, the result may vary.

Key Synchronization Concepts:

• Synchronized Method: When a method is declared synchronized,


only one thread can access that method at a time for a given object.

public synchronized void increment()


{
// Critical section
}

• Synchronized Block: Only a specific part of the code (within a


block) is synchronized. This can improve performance as only the
critical section is locked, while the rest of the method can execute
concurrently.
synchronized (this)
{
// Critical section
}

• Static Synchronization: If you declare a static method as


synchronized, the lock will be on the class object, not on any
instance of the class.

public static synchronized void method()


{
// Critical section
}
Example: Synchronizing Access to Shared Resources

class Counter {
private int count = 0;

public synchronized void increment() {


count++; // Critical section
}

public int getCount() {


return count;
}
}

class MyThread extends Thread {


Counter counter;

MyThread(Counter counter) {
this.counter = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
counter.increment();
} } }

public class Test {


public static void main(String[] args) throws InterruptedException
{
Counter counter = new Counter();
MyThread t1 = new MyThread(counter);
MyThread t2 = new MyThread(counter);
t1.start();
t2.start();
t1.join(); // Wait for t1 to finish
t2.join(); // Wait for t2 to finish
System.out.println("Final count: " + counter.getCount());
} }

Explanation: The method increment() is synchronized, ensuring that


only one thread can increment the counter at a time, preventing thread
interference.

Multithreading in Java:
➢ Multithreading is a process of executing multiple threads
simultaneously within a program. In Java, multithreading is a key
feature that allows the efficient use of CPU by sharing its time between
different threads (also known as time-slicing or concurrency).
Key Concepts in Multithreading:

➢ Thread: The smallest unit of processing. In Java, every thread runs


in the context of a process.
➢ Multitasking: The process of executing multiple tasks
simultaneously.
o Process-based Multitasking: Each process is independent and
has its own memory space.
o Thread-based Multitasking: Multiple threads share the same
process space and resources.

Benefits of Multithreading:
➢ Improved Performance: Multithreading enhances the overall
performance of a program by allowing multiple tasks to run
concurrently.
➢ Resource Sharing: Threads share the same memory and
resources, making it efficient to work with shared data.
➢ Responsiveness: Multithreading helps to create responsive
applications. For example, a thread can handle background tasks
while another thread handles user input.
Example of Creating Multiple Threads:
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is running...");
} }
public class Test
{
public static void main(String[] args)
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Start the first thread
t2.start(); // Start the second thread
} }
Here, two threads t1 and t2 run concurrently, and their outputs may
interleave.
Thread Lifecycle in Multithreading:

1. New: A thread is in this state when it is created but not yet started.
2. Runnable: The thread is ready to run and waiting for CPU time.
3. Running: The thread is actively running.
4. Blocked/Waiting: The thread is waiting for a resource or another
thread.
5. Terminated: The thread has finished executing.
Thread Example with sleep() and join():
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i + " - " + Thread.currentThread().getName());
} } }
public class Test
{
public static void main(String[] args) throws InterruptedException
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Start thread 1
t2.start(); // Start thread 2
t1.join(); // Main thread waits for t1 to finish
t2.join(); // Main thread waits for t2 to finish
System.out.println("Both threads have completed.");
} }

Explanation:
➢ sleep(1000) makes each thread sleep for 1 second between prints.
➢ join() ensures that the main thread waits for both t1 and t2 to finish
before proceeding.
Thread Synchronization Example:
class Table {
synchronized void printTable(int n) { // Synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
} }} }
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
public void run() {
t.printTable(5); // Print table of 5
} }
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
public void run() {
t.printTable(100); // Print table of 100
} }
public class Test {
public static void main(String args[]) {
Table obj = new Table(); // Only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
} }

Explanation:
➢ The printTable() method is synchronized, so when one thread
accesses it, the other must wait until the first thread finishes,
preventing interleaving.
Note:

Thread Operations: Methods like start(), sleep(), join(), interrupt(), and


yield() control thread behavior.
Thread Synchronization: Use synchronized methods or blocks to
prevent thread interference and ensure data consistency when multiple
threads access shared resources.
Multithreading: Enables concurrent execution of multiple threads,
optimizing performance and responsiveness, but requires careful
management of shared resources using synchronization.

Generic Collections - Generic Classes and Methods

What are Generics?

➢ Generics enable types (classes and methods) to be parameterized by type


arguments.
➢ They provide type safety and reusability.
➢ Key use cases:
✓ Creating collections or data structures that work with multiple
types.
✓ Writing methods that can process data of different types.

Generic Collections:

➢ Definition: Collections in java.util package (e.g., ArrayList, HashMap) are


implemented using generics.
➢ Generics make collections type-safe:
✓ Specify the type of elements they store.
✓ Prevent runtime errors caused by type mismatches.
Examples:
1. ArrayList with Generics:
import java.util.ArrayList;
public class GenericCollectionDemo
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// names.add(10); // Compile-time error
for (String name : names)
{
System.out.println(name);
} } }
Advantage: Type-safe, avoids explicit type casting.

2. HashMap with Generics:


import java.util.HashMap;
public class GenericMapDemo
{
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
// map.put(3, 10); // Compile-time error
for (var entry : map.entrySet())
{
System.out.println(entry.getKey() + " = " + entry.getValue());
} } }

Generic Classes:

Definition: A class can be declared with one or more type parameters.

Syntax:

class ClassName<T>
{
private T value;
ClassName(T value)
{
this.value = value;
}
T getValue()
{
return value;
} }

Example:

public class GenericClassDemo<T>


{
private T data;
public GenericClassDemo(T data)
{
this.data = data;
}

public T getData()
{
return data;
}

public static void main(String[] args)


{
GenericClassDemo<Integer> intObj = new GenericClassDemo<>(123);
System.out.println("Integer Value: " + intObj.getData());
GenericClassDemo<String> stringObj = new GenericClassDemo<>("Hello");
System.out.println("String Value: " + stringObj.getData());
}
}

Generic Methods:

➢ Definition: A method can be declared with type parameters, making it


independent of class-level type parameters.

Syntax:
public <T> void methodName(T param)
{
// Method body
}
Example:
public class GenericMethodDemo
{
public static <T> void printArray(T[ ] array)
{
for (T element : array)
{
System.out.print(element + " ");
}
System.out.println();
}

public static void main(String[] args)


{
Integer[] intArray = {1, 2, 3};
String[] strArray = {"A", "B", "C"};
printArray(intArray); // Output: 1 2 3
printArray(strArray); // Output: A B C
}
}

Bounded Types:

➢ Definition: Restrict the type arguments to a specific superclass or interface.

Syntax:
class ClassName<T extends SuperClass>
{
// T must be SuperClass or its subclass
}
Example:
class Stats<T extends Number>
{
T[ ] nums;
Stats(T[] nums) {
this.nums = nums;
}
double average() {
double sum = 0.0;
for (T num : nums) {
sum += num.doubleValue();
}
return sum / nums.length;
}
}
public class BoundedTypeDemo {
public static void main(String[] args) {
Integer[] inums = {1, 2, 3, 4, 5};
Stats<Integer> iStats = new Stats<>(inums);
System.out.println("Average of integers: " + iStats.average());
Double[] dnums = {1.1, 2.2, 3.3};
Stats<Double> dStats = new Stats<>(dnums);
System.out.println("Average of doubles: " + dStats.average());
} }

Wildcards in Generics:
➢ Definition: A placeholder for an unknown type.
Types of Wildcards:
1. Unbounded (?):
➢ Accepts any type.
Example: List<?>

2. Bounded Upper (? extends T):


➢ Accepts T or its subclasses.
➢ Example: List<? extends Number>

3. Bounded Lower (? super T):


➢ Accepts T or its superclasses.
➢ Example: List<? super Integer>
Example:
import java.util.List;
import java.util.ArrayList;
public class WildcardDemo
{
public static void printList(List<?> list)
{
for (Object obj : list)
{
System.out.println(obj);
}
}
public static void main(String[] args)
{
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
List<String> strList = new ArrayList<>();
strList.add("A");
strList.add("B");
printList(intList); // Accepts any type
printList(strList);
}
}

Multiple Bounds:
➢ Definition: A type parameter can extend multiple classes/interfaces
using the & operator.
Syntax:
class ClassName<T extends Class & Interface>
{
// Body
}
Example:
interface Printable
{
void print();
}
class BaseClass {
void show() {
System.out.println("Base class method");
}
}
class MultiBound<T extends BaseClass & Printable> {
T obj;
MultiBound(T obj) {
this.obj = obj;
}
void display() {
obj.show();
obj.print();
}
}
class DerivedClass extends BaseClass implements Printable {
public void print() {
System.out.println("Printable method");
}
}
public class MultiBoundsDemo {
public static void main(String[] args) {
DerivedClass obj = new DerivedClass();
MultiBound<DerivedClass> mb = new MultiBound<>(obj);
mb.display();
}
}
Output:
Base class method
Printable method

Advantages of Generics:
➢ Type Safety: Eliminates runtime type mismatch errors.
➢ Eliminates Casting: No need for explicit type casts.
➢ Code Reusability: Single codebase works with multiple data types.
➢ Improved Performance: Reduces the overhead of type checking and
casting.

You might also like