All Units
All Units
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens
in Java Programs, Java Statements, Command Line Arguments, User Input to Programs, Escape
Sequences, Comments, Programming Style.
Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of
Variables, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants,
Formatted Output with printf() Method, Static Variables and Methods, Attribute Final,
Introduction to Operators, Precedence and Associativity of Operators, Assignment Operator
( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -) Operators, Ternary
Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical Operators.
4. Secure:-
Java is a secure programming language because it has no explicit pointer and programs runs in
the virtual machine. Java contains a security manager that defines the access of Java classes.
5. Multi Threading:-
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
6. Architectural Neutral:-
Compiler generates byte codes, which have nothing to do with particular computer architecture;
hence a Java program is easy to interpret on any machine.
7. Portable:-
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't
require any implementation. For example, the size of primitive data types.
8. High Performance:-
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.
9. Distributed:-
Java is distributed because it facilitates users to create distributed applications in Java. This
feature of Java makes us able to access files by calling the methods from any machine on the
internet.
10. Dynamic:-
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++. Java supports
dynamic compilation and automatic memory management (garbage collection).
11. Robust:-
Java makes an effort to check error at run time and compile time. It uses a strong memory
management system called garbage collector. Exception handling and garbage collection
features make it strong.
Conpect-2 Writing Simple Java Programs
Output:-
The main() method of every Java program only accepts string arguments. Hence it is not
possible to pass numeric arguments through the command line.
However, we can later convert string arguments into numeric values.
Example Program:- Illustration Concept of the Numeric Command Line Arguments
Output:-
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,
Arrays, and String.
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.
Boolean data type variable are used in the dealing with logical statements.
Its default value is false.
Example: boolean one = false
Integers Number
Integer are whole number that is, they represent number that do not have a fractional part.
The integer can be declared in four types according to the size of memory allocated.
1. byte 2. short 3. int 4. long
Byte Data Type
The byte data type is an example of primitive data type.
It is an 8-bit signed integer. That is 1 byte
Its value-range lies between -128 to 127.
Its minimum value is -128 and maximum value is 127.
Its default value is 0.
Example: byte a = 10, byte b = -20
short Data Type
The short data type is a 16-bit signed integer. That is 2 byte.
Its value-range lies between -32,768 to 32,767 (inclusive).
Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.
Example: short s = 10000, short r = -5000
int Data Type
The int data type is a 32-bit signed integer. That is 4 byte.
Its value-range lies between -2,147,483,648 or (-2^31) to 2,147,483,647 or (2^31 -1).
Its minimum value is -2,147,483,648 and maximum value is 2,147,483,647.
Its default value is 0.
Example: int a = 100000, int b = -200000
long Data Type
The long data type is a 64 bit signed integer. That is 8 byte.
The value-range lies between -9,223,372,036,854,775,808 or (-2^63) to
9,223,372,036,854,775,807 or (2^63 -1)
Its minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807.
Its default value is 0.
Example: long a=123455334453, long b=3123453211343
Float point number
The numbers that are not whole numbers, or those that have fractional part, Examples are
3.141, 476.6, and so on.
Java supports two types of such numbers
Float Data Type
Types of Variables
There are three types of variables in Java
1. local variable 2. instance variable 3. static variable
Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in the class.
A local variable cannot be defined with "static" keyword.
Instance variable
A variable declared inside the class but outside the body of the method, is called instance
variable.
It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
Static variable
A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the
memory. Example:
int x = 10;
Compound Assignment operators
Arithmetic Operator
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division.
They act as basic mathematical operations.
The operands of the arithmetic operators must be of a numeric type.
Cannot use them on boolean type.
This arithmetic operator is the binary operator that is to perform the operation it required
the two operands.
% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0
The + operator can also be used to concatenate two or more strings.
Program
Program
Program
Ternary Operator (?:)
The conditional operator or ternary operator ?: is shorthand for the if-then-else statement.
The syntax of the conditional operator is:
variable = Expression ? expression1 : expression2
Here's how it works.
If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.
Program
Relational Operator
The relational operators determine the relationship between the two operands.
It checks if an operand is greater than, less than, equal to, not equal to and so on.
Depending on the relationship, it is evaluated to either true or false.
Relational operators are used in decision making and loops.
Program
Output:-
Program
Output:-
Bitwise Operator & Bit Shift Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs the bit-by-bit operation.
Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands.
If both bits are 1, it gives 1. If either of the bits is not 1, it gives 0.
Program on Bitwise AND
Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands.
If either of the bits is 1, it gives 1. If not, it gives 0.
Program on Bitwise OR
Bitwise NOT
It is also called as Bitwise complement.
It is a unary operator (works on only one operand).
It is denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
Special operators
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false.
Program
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
Output:-
Selection Statements
Statements that determine which statement to execute and when are known as Selection
statements.
The flow of the execution of the program is controlled by the control flow statement.
Statement allow you to control the flow of your program execution based upon conditions
known only during runtime.
Selection statements are as follows
1. Simple If statement
2. If else statement
4. Nested if statement
5. Switch statement
Simple if statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax
Program
Output:-
If else statement
The Java if-else statement also tests the condition.
It executes the if block if condition is true otherwise else block is executed.
Syntax
Program:-
Output:-
If else-if ladder statement
The if-else-if ladder statement executes one condition from multiple conditions.
It is the any form of switch statement.
Syntax
Program:-
Output:-
Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
Syntax
Program:-
Output:-
Switch statement
It is like if-else-if ladder statement.
The Java switch statement executes one statement from multiple conditions.
The switch statement tests the equality of a variable against multiple values.
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only.
The case value must be constant. It doesn't allow variables.
The case values must be unique. In case of duplicate value, it renders compile-time error.
Each case statement can have a break statement which is optional. When control reaches
to the break statement, it jumps the control after the switch expression.
If a break statement is not found, it executes the next case.
The case value can have a default label which is optional.
The Java switch expression must be of byte, short, int, long, char and string.
Syntax
Program:-
Iterative Statements / Looping statement
Loops are used to execute a set of instructions/functions repeatedly when some conditions
become true.
Iterative statements are as follows
1. while Loop
2. do-while loop
3. for loop
4. for-each loop
While Loop
while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed, it is recommended to use while loop.
Syntax
Program
Infinitive While Loop
do-while Loop
do-while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop at least once,
it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax
Program
For Loop
The Java for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.
In Java for loop is the same as C/C++.
We can initialize the variable, check condition and increment/decrement value.
It consists of four parts:
1.Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable.
It is an optional condition.
2.Condition: It is the condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false.
It must return boolean value either true or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the condition is false.
4. Increment/Decrement: It increments or decrements the variable value.
It is an optional condition.
Syntax
Program
Jump Statement
The Java jumping statements are the control statements which transfer the program execution
control to a specific statement.
These statements transfer execution control to another part of the program.
Java has three types of jumping statements
1.break 2. continue
Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
It breaks the current flow of the program at specified condition.
We can use break statement in the following cases.
Inside the switch case to come out of the switch block.
Within the loops to break the loop execution based on some condition.
Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax
Program
Continue Statement
The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately.
The Java continue statement is used to continue the loop.
It continues the current flow of the program and skips the remaining code at the specified
condition.
Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax
Program
Concept-10 Elements or Tokens in Java Programs
Java tokens are elements of java program which are identified by the compiler
Elements of Java (OR)
Keywords
Keywords also known as reserved words or pre-defined words that have special meaning to
compiler.
Keywords cannot be used as name of variables, methods, classes, or packages.
All keywords must be used in lower case only and white space not allowed.
Identifier
Identifier is the name of variables, methods, classes etc.
Java is a case sensitive language.
Rules for framing Names or Identifiers.
1. It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
underscore (_).
2. It should not contain white spaces and special symbols.
3. It should not be a keyword of Java.
4. It should not start with a digit but it can start with an underscore.
Conventions for Writing Names
1. Names of packages are completely in lower-case letters such as mypackage, java.lang.
2. Names of classes and interfaces start with an upper-case letter.
3. Names of methods start with a lower-case character.
4. Names of variables should start with a lower-case character.
Separators
These include comma (,) , semicolon (;), period(.), Parenthesis (), Square brackets [], etc.
Literals:-
Literal is a notation that represents a fixed value in the source code.
Literals are the constant values that appear directly in the program.
It can be assigned directly to a variable.
A literal represents a value which may be of primitive type, String type, or null type.
The value may be a number (either whole or decimal point number) or a sequence of
characters which is called String literal, Boolean type, etc.
Types of Literals
1. Integer literals:-
Sequences of digits.
The whole numbers are described by different number systems such as decimal numbers,
hexadecimal numbers, octal numbers, and binary numbers.
Each number has a different set of digits. Types of Integer Literals
a. Decimal Integer Literals b. Hex Integeral Literals c. Octal Integer Literals d.Binary Literals
a. Decimal Integer Literals
These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
Examples of such literals are 6, 453, 34789, etc.
b. Hex Integeral Literals
These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D,
E, and F.
The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and f.
The numbers are preceded by 0x or 0X.
Examples are 0x56ab, o0X6AF2, etc.
c. Octal Integer Literals
These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
d. Binary Literals
These are sequences of binary digits.
Binary numbers have only two digits 0 and 1 and a base 2.
These numbers are preceded by 0b.
Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
2. Floating point literal
These are floating decimal point numbers or fractional decimal numbers with base 10.
Examples are 3.14159, 567.78, etc.
3. Boolean literal
These are Boolean values. There are only two values true or false.
4. Character literal
These are the values in characters.
Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
5. String literal
These are strings of characters in double quotes. Examples are “Delhi”, “John”, “AA”, etc.
6. Null literal
There is only one value of Null Literal, that is, null.
Escape Sequences
Escape Sequences character is preceded by a backslash (\) has a special meaning to the
compiler.
Program
Comments
Comments are Line of Text which is not a part of the compiled program.
Comments are used for documentation to explain source code.
They are added to the source code of the program.
Java supports three types of comments as:
1. Single-line comment:
These comments are started with two front slash characters (//)
Example: // This is Single line comment
2. Multi-line comment :
These comments are enclosed with /* and */
Example: /* It is Multi line Comments */
3. Documentation comment:
These comments are enclosed with /** and */.
It is different from multi line comments in that it can extracted by javadoc utility to generate
an HTML document for the program.
Example: /** It is documentation Comments */
Concept-11 Type Casting
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.
Static Methods
Static method in Java is a method which belongs to the class and not to the object.
A static method can access only static data.
It cannot access non-static data (instance variables).
Static variables and methods can be accessed using the class name followed by a dot and the
name of the variable or method.
Syntax <class-name>.<method-name>
For example The method like sqrt() is a static method in a Math class.
Math.sqrt(5);
Program
Concept-13 Attribute Final
Final Variable
The value of a variable declared final cannot be changed in the program.
It makes the variable a constant.
A few examples of declarations are as follows:
final double PI = 3.14159; // The value of PI cannot be changed in its scope
final int M = 900; // The value of M cannot be changed in its scope
final double X = 7.5643; // The value of x cannot be changed in its scope.
As mentioned in the comments, the values of PI, M, and x cannot be changed in their
respective scopes.
The attribute final may be used for methods as well as for classes.
Final Method
When final keyword is used with Java method, it becomes the final method.
These are basically connected with inheritance of classes.
A final method cannot be overridden in a sub-class.
Final Class:
A Java class with final modifier is called final class
A final class cannot be sub-classed or inherited.
Several classes in Java are final including String, Integer, and other wrapper classes.
There are certain important points to be noted when using final keyword in Java
i. New value cannot be reassigned to a variable defined as final in Java.
ii. Final keyword can be applied to a member variable, local variable, method, or class.
iii. Final member variable must be initialized at the time of declaration.
iv. Final method cannot be overridden in Java
v. Final class cannot be inheritable in Java
Concept-14 Formatted Output with printf() Method
The formatting of output may be carried out by method printf()
The syntax of the method printf () method is as follows
System.out.printf("Formatting string" variables separated by comma);
System.out.printf(“Price of this item = %d”, 22 , “Rupees.”);
The arguments in the example
1. “Price of this item=” It is a string that is displayed as aforementioned.
2. “%d” It is a formatting string for displayed of integer, that is, 22.
3. “Rupees.” A String that is displayed as written here.
Output:- Price of this item = 22 Rupees.
Program:-
Output:-
Important Question
1. Explain various Key Words available in Java.
2. Discuss the rules in Automatic Type Promotion in Expressions.
3. Explain various Operators in Java.
4. Write a Java Program to test whether a given character is Vowel or Consonant.
5. Write a Java Program to swap two numbers using bitwise operator.
6. Write a Java Program to find sum of natural numbers.
7. Write a Java Program to convert decimal number into a hexdecimal number.
8. Write a Java Program to convert decimal number into a binary number.
9. Write a Java Program to find the factorial of a given number.
10. Write a Java Program to find the area of triangle.
11. What are the basic (Primitive) data types defined in java.
12. How do you declare a variable and understand by scope of an identifier for a variable.
13. How is the Scanner class used by a user to input data into a program.
14. How do you declare a constant in java.
15. What is type casting? Explain with an example of automatic type casting and explicit type
casting.
16. Explain the table of Precedence and Associativity of Operators.
17. What are the different type’s selection statements in java?
18. What are the different types of looping and jump statements in java?
19. Explain type of element or token in Java Programming.
20. Explain in detail about Command Line Arguments in Java.
21. Write a short on Static Methods ,Variable and attribute final in Java.
UNIT-2
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value
and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor
Methods, Class Objects as Parameters in Methods, Access Control, Recursive Methods,
Nesting of Methods, Overriding Methods, Attributes Final and Static.
Example:
The class name starts with an upper-case letter, whereas variable names may start with
lower-case letters.
In the case of names consisting of two or more words as in MyFarm, the other words
for with a capital letter for both classes and variables.
In multiword identifiers, there is no blank space between the words.
The class names should be simple and descriptive.
Class names are nouns.
For example, it could include names such as vehicles, books, and symbols.
Acronyms and abbreviations should be avoided.
Class Modifier
Class modifiers are used to control the access to class and its inheritance characteristics.
Java consists of packages and the packages consist of sub-packages and classes
Packages can also be used to control the accessibility of a class
These modifiers can be grouped as (a) access modifiers and (b) non-access modifiers.
Example of class Declarations
1. A class without a modifier is declared with keyword class followed by name/identifier of
class, and name is followed by a pair of braces { }.
package pack1;
class Myclass{
/* class body */
}
A class must belong to a package. If a programming does not specify a package, the class is
placed in the default package generated by a compiler.
2. A class with modifier is declared as follows
package pack1;
public class Myclass{
/* class body */
}
This class is visible to all other classes in any package.
3. The modifier class with private and protected is used only for nested class.
package pack1;
class X{
Statements;
private class Myclass
{ // Class body
}
}
A private class is declared inside another class. Therefore, this class is visible to other member
of the enveloping class in which it is declared. For all other classes, this class is not visible.
4. Class with the final modifier are declared as follows
package pack1;
final class Myclass{
// Class body
}
A class with the modifier final cannot be extended that is cannot have subclasses but it can
have a super class.
5. Class with the abstract modifier are declared as follows
package pack1;
abstract class Myclass{
abstract void display();
}
A class declared abstract must have one or more abstract methods as its members that is
methods without a body; it is only the header of a method followed by semicolon.
Concept-3 Class Members
The class members are declared in the body of a class.
The class member may contain fields (variables in a class), methods, nested classes, and
interfaces.
The member of a class contains the members declared in the class as well as the members
inherited from a super class.
The scope of all the members extends to the entire class body.
There are two type of variable
1.Non Static variables: These include instance and local variables and vary in scope and value.
(a) Instance variables: These variables are individual to an object and an object keeps a copy
of these variables in its memory.
(b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables (Static Variables): These variables are also contains as static keyword. The
values of these variables are common to all the objects of the class.
Program:-
Concept-4 Declaration of Class Objects
Creating an object is also referred to as instantiating an object.
Objects in java are created dynamically using the new operator.
The new operator creates an object of the specified class and returns a reference to that
object.
Syntax: class_name object_name;
For Example A Class defined as
public class Farm{
int length;
int width;
}
An Object of class Farm may be declared as null
Farm myFarm;
Here, the variable myFarm simply refers to an object of Farm class whose value at present is
null;
The new operator creates a new object or an instance of a class. With this, the objects are
created.
The memory is allocated dynamically in the heap at runtime of the program.
Object_name = new className();
Here, myFarm is a variable of the type Farm. Each object of the Farm class has allocated
memory that can hold the values of instance variables length and width.
Definition/Creation of object
Program:-
Output:-
Output:-
Program:-
Parameterized constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Arguments can be passed to the constructor in order to initialize the instance variable of an
object.
It has a mechanism for automatically initializing the values for objects as soon as the object
is created. This mechanism is called as constructors.
Program:-
Concept-9 Final Class and Methods
Final Class
A class that is declared with the final keyword is known as the final class.
A final class can’t be inherited by subclasses.
By use of the final class, we can restrict the inheritance of class.
In java, all the wrapper classes are final class like String, Integer, etc.
If we try to inherit a final class, then the compiler throws an error at compilation time.
We can create a class as a final class only if it is complete in nature it means it must not be
an abstract class.
Syntax:
accessModifier final class className
{
// Body of class
}
Program:-
Final Method
We can declare a method as final, once you declare a method final it cannot be overridden.
So, you cannot modify a final method from a sub class.
The main intention of making a method final would be that the content of the method should
not be changed by any outsider.
Syntax:-
final accessmodifier datatype methodname(Parameter….){
// Method body
}
Program:-
Concept-10 Passing Arguments by Value and by Reference
Call by Value:
Call by Value means calling a method with a parameter as value. Through this, the argument
value is passed to the parameter.
In call by value, the modification done to the parameter passed does not reflect in the caller's
function.
Any modification done in called function will not affect the original value. i.e., actual and
formal parameters are different
Program: Output:-
Call by Reference
Call by Reference means calling a method with a parameter as a reference. Through this, the
argument reference is passed to the parameter.
In call by reference the object will be passed to the method as an argument.
In the call by reference, the modifications done to the parameter passed are persistent and
changes are reflected in the caller's function.
That means any occurs in actual arguments will be reflected in the formal arguments.
Program: Output:-
Output:-
Concept-14 Class Objects as Parameters in Methods
Object as an argument is use to establish communication between two or more objects
of same class.
Objects can be passed as parameters to the Methods just like primitive data types.
It is called as Call by Reference.
When a primitive type is passed to a method, it is done by use of call-by-value.
Objects are implicitly passed by use of call-by-reference.
This means when we pass primitive data types to method it will pass only values to
function parameters so any change made in parameter will not affect the value of
actual parameters.
Program:-
Output:-
Concept-15 Recursive Methods
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
Example:-
Program:-
Output:-
Concept-16 Nesting of Methods
A method of a class can be called only by an object of that class using the dot operator
(.) So, there is an exception to this.
A method can be called by using only its name by another method of the same
class that is called Nesting of Method.
Program:-
Concept-17 Overriding Methods
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
1. Method overriding is used for runtime polymorphism
Output:-
Important Question
1. Explain the concept of call by value and call by reference with an example.
2. Explain the concept of Nesting of Methods with an example.
3. Discuss the significance of overriding methods with a program.
4. Write a Java method to find the minimum values in given two values
5. Explain the need for recursive methods in Java with an example.
6. Explain the difference between method overloading and constructor overloading with
examples.
7. What access modifiers may be used with in a class? How do you access a methods
declared private in a class?
8. What is the constructor methods in a Java explain with an example program?
9. Write a short note on this keyword in Java?
10. Explain about final class and final method in Java?
11. What is a class and object? How to declared and class and object in Java with an
example program?
12. Explain about Assigning One Object to Another object in Java with an example?
13. Explain about class member of class in Java?
UNIT-3
Arrays: Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer
Memory, Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to
Another Array, Dynamic Change of Array Size, Sorting of Arrays, Search for Values in Arrays,
Class Arrays, Two-dimensional Arrays, Arrays of Varying Lengths, Three dimensional Arrays,
Arrays as Vectors.
Inheritance: Introduction, Process of Inheritance, Types of Inheritances, Universal Super
Class-Object Class, Inhibiting Inheritance of Class Using Final, Access Control and
Inheritance, Multilevel Inheritance, Application of Keyword Super, Constructor Method and
Inheritance, Method Overriding, Dynamic Method Dispatch, Abstract Classes, Interfaces and
Inheritance.
Interfaces: Introduction, Declaration of Interface, Implementation of Interface, Multiple
Interfaces, Nested Interfaces, Inheritance of Interfaces, Default Methods in Interfaces, Static
Methods in Interface, Functional Interfaces, Annotations.
➢ 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.
➢ 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.
➢ For Example:- If the array elements have values in whole numbers, that is the type of array
is also int. If it is a sequence of characters, the type of array is char.
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.
There are three types of array.
1. Single Dimensional Array 2. Two Dimensional Array 3. Multidimensional Array
➢ The type refers to the type of the data that the array holds, identifier is the name of the array.
➢ The square bracket indicates that it is an array.
Examples:
int numbers []; // an array of whole numbers
char name []; // A name is an array of characters
float priceList []; // An array of floating point numbers.
➢ After array declaration no memory is allocated. Memory is allocated when the operator
new is used or when it is initialized along with a declaration.
Example: datatype identifier[]=new datatype[size];
int number[]=new int[4] //allocates 4 memory spaces
➢ The above code allocates memory for 4 int type elements of the array named numbers.
The values of the elements are default equal to 0.
Initialization of Arrays:
➢ An array may be initialized by mentioning the values in braces and separated by commas.
For example, the array pencils may be initialized as below:
int pencils [] = {4, 6, 8, 3};
➢ Each element of an array has an index value
Alternative Array Declaration Syntax:
➢ Java also supports the following type of code for array declaration.
type[] identifier; // declares one dimensional array
Example: int [] numbers; char [] name; float [] pricelist;
➢ This notation is useful when several arrays of the same type are to be declared.
Example: int [] numbers, items; // declares two arrays
Concept-3 Storage of Array in Computer Memory
➢ The operator new allocates memory for storing the array elements. For example, with the
following declaration int[] numbers = new int[4];
➢ Here 4 elements will be created and assigned to the array “numbers”
➢ When an array is created as above, element of the array is automatically initialized to 0
by the compiler.
➢ After allocation of memory as above, each member may be assigned a value by accessing it
by its index value.
number[0]=10; number[1]=20; number[2]=30; number[3]=50;
➢ The declaration and initialization may as well be combined as:
int numbers [] = {20,10,30,50};
Program:-
Output:-
Concept-4 Accessing Elements of Arrays
➢ The individual member of an array may be accessed by its index value.
➢ The index value represents the place of element in the array.
➢ The first element space is represented by numbers [0], and index value is 0.
➢ Note that the value of an array element is different from its index value.
Example: int numbers [] = {20,10,30,50};
Determination of Array Size
➢ The size or length of an array may be determined using the following code:
int arraySize = array_identifier.length;
➢ The size of array numbers is determined as:
int size = numbers.length;
➢ The elements of a large array may be accessed using a for loop.
➢ For example, the elements of array numbers may be accessed as
for (int i = 0; i<size;i++){
System.out.println(numbers[i]);
}
Use of for–each Loop
➢ The for–each loop may be used to access each element of the array.
for (int x: numbers)
System.out.println(x);
Program on array size:-
Program on for–each Loop:-
Output:-
Concept-6 Dynamic Change of Array Size
➢ Java allows us to change the array size dynamically during the execution of the program.
➢ In C and C++ where the array is once declared it size fixed, that is, the number of elements
cannot be changed.
➢ We may change the number of elements by dynamically but we can retain the name of array.
➢ In this process the old array is destroyed along with the values. After change the array size
the element are destroyed and that array is default initialized to the 0.
Program:-
Concept-7 Sorting of Arrays
➢ Sorting of arrays is a main applications of an arrays.
➢ We need to sort the given array in ascending order such that elements will be arranged from
smallest to largest or largest to smallest.
Program:-
Output:
Output:-
Concept-9 Arrays of Varying Lengths
➢ A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we
can create a 2-D array but with a variable number of columns in each row.
➢ These types of arrays are also known as Jagged arrays or non-rectangular arrays.
➢ You have to first declare and instantiate the array by specifying only the number of
elements in the first dimension and leaving the second dimension empty.
For example: int [] [] table = new int [3] [];
➢ The arrays may as well be declared as
int array [][] = {{5, 7, 8 },{10, 11 }, {4, 3, 2, 7,5 }};
Program:-
Output:-
Concept-10 Three dimensional Arrays
➢ Three-dimensional array is the collection of two-dimensional arrays in Java programming
language.
➢ Three-dimensional array is also called the multidimensional array.
➢ Each basic element of such an array needs three index values for its reference.
Output:-
Concept-11 Class Arrays
➢ Arrays class is predefined class available in the java to create the array in java.
➢ The package java.util defines the class Arrays with static methods- for general process
that are carried out operation on arrays such as
1. sorting an array for full length of the array or for part of an array,
2. binary search of an array for the full array or part of an array,
3. for comparing two arrays if they are equal or not,
4. for filling a part or the full array with elements having a specified value.
5. for copying an array to another array
Sort
This method defines to sort the element in order.
This class contains several overload methods for sorting arrays of different types.
Example: public static void sort (int[] array)
Equals
Example: public static boolean equals (int [] a, int [] b)
The output is a Boolean value—it returns true, if the elements and their order in the two arrays
are same; otherwise, it returns false.
Fill
The two versions of method fill defined in class Arrays are as follows.
Example: public static void fill (byte [] array, byte value)
The method fills the entire array with a specified value.
Example: public static void fill(byte [] array, int startIndex, int endIndex, byte value)
The method fills the specified subset of an array with the specified value.
CopyOf
Example: public static byte [] copyOf(byte [] original, int length)
The method copies the array into a new array of specified length
copyOfRange
public static char [] copyOfRange( char [] original, int fromIndex, int toIndex)
The method copies a specified range of elements into a new array of specified length.
toString
public static String toString (int [] array)
The method returns a string representation of the array elements.
Program:-
Output:-
Program:
Concept-13 Inheritance: Introduction, Process of Inheritance
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
➢ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
➢ Reusability: Reusability is a mechanism which facilitates you to reuse the fields and methods
of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.
Disadvantages of Inheritance
1. The tight coupling between super and subclasses increases and it becomes very difficult to
use them independently.
2. Program processing time increases as it takes more time for the control to jump through
various levels of overloaded classes.
3. When some new features are added to super and derived classes as a part of maintenance,
the changes affect both the classes.
4. When some methods are deleted in super class that is inherited by a subclass, the methods
of subclass will no longer override the super class method.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
The syntax of Java Inheritance
Output:-
Output:-
➢ Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class. the class A serves as a base class for the derived class B,C
and D.
Program:
Output:-
➢ Multiple Inheritances (Through Interfaces): In Multiple inheritances, one class can have
more than one superclass and inherit features from all parent classes.
➢ Java does not support multiple inheritances with classes. In java, we can achieve multiple
inheritances only through Interfaces.
➢ Class C is derived from interface A and B.
Program:
Output:-
} }
Object Class Constructor
➢ Object() This is the Single Constructor in the object class and it is default constructor.
➢ It is important to be familiar with the methods provided by the object class so that you can
use then in your classes.
Method of the Object Class
Method Description
public boolean equals(Object obj) compares the given object to this object.
public String toString() returns the string representation of this object.
This method is called by the garbage collector on an object
protected void finalize() when garbage collection determines that there are no more
references to the object.
Program:
Output:-
Concept-15 Access Control and Inheritance
➢ A derived class access to the members of a super class may be modified by access specifiers.
➢ There are three access specifiers, that is, public, protected, and private.
➢ The code for specifying access is Access-specifier type member_identifier;
Program:-
Concept-17 Method Overriding
Difference between Method Overriding & Method Overloading
Method Overloading Method Overriding
Method overriding is used to provide the
Method overloading is used to increase the
specific implementation of the method that is
readability of the program.
already provided by its super class.
Method overloading is performed within Method overriding occurs in two classes that
class. have IS-A (inheritance) relationship.
In case of method overloading, parameter In case of method overriding, parameter must
must be different. be same.
Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
In java, method overloading can't be
performed by changing return type of the
method only. Return type can be same or Return type must be same in method
different in method overloading. But you overriding.
must have to change the parameter.
Binding
➢ Association of method call with the method body is known as binding.
➢ There are two types of binding:
Static binding that happens at compile time
And
Dynamic binding that happens at runtime.
Static Binding or Early Binding
➢ The binding which can be resolved at compile time by compiler is known as static or early
binding. The binding of static, private and final methods is compile-time.
➢ Binding of static, private and final methods happen, type of the class is determined by the
compiler at compile time and the binding happens them.
Program
Output:
Output:
Concept-18 Dynamic Method Dispatch
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Program:
Concept-19 abstract classes
➢ A class which is declared with the abstract keyword is known as an abstract class in Java.
Example:- abstract class A{ }
➢ It can have abstract and non-abstract methods (method with the body).
➢ It needs to be extended and its method implemented.
➢ It cannot be instantiated. (object creating is not possible)
Points to Remember Example:- abstract void run();
➢ An abstract class must be declared with an abstract keyword.
➢ It can have abstract and non-abstract methods.
➢ It can have constructors and static methods also.
➢ If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
Abstract Method in Java
➢ A method which is declared as abstract and does not have implementation is known as an
abstract method.
Program:-
Output:-
Concept-20 Interfaces: Introduction, Declaration of Interface
Introduction
➢ An interface in Java is a blueprint of a class.
➢ It has static final data members and abstract methods.
➢ The interface in Java is a mechanism to achieve abstraction.
➢ There can be only abstract methods in the interface, not method body.
➢ It is used to achieve abstraction and multiple inheritances in Java.
➢ In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
➢ Interface also represents the IS-A relationship.(Single Inheritance).
➢ It cannot be instantiated (object creation is not possible) just like the abstract class.
Why use Java interface?
➢ There are mainly two reasons to use interface. They are given below.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritances.
Declaration of interface
➢ An interface is declared by using the interface keyword.
➢ It provides total abstraction; means all the methods in an interface are declared with the empty
body, and all the fields (data members) are public, static and final by default.
➢ A class that implements an interface must implement all the methods declared in the interface.
Syntax of the interface
➢ A class implementing an interface must provide implementation for all its methods unless it is
an abstract class.
➢ Example:
Program
Concept-23 Nested Interfaces
➢ An interface, i.e., declared within another interface or class, is known as a nested interface.
➢ The nested interfaces are used to group related interfaces so that they can be easy to maintain.
➢ The nested interface must be referred to by the outer interface or class. It can't be accessed
directly.
Syntax of nested interface
Program
Concept-24 Inheritance of Interfaces
➢ Inheritance of Interfaces is similar to the Inheritance of classes. Interface can be derived from
another interface.
Syntax:
Example:
Program:
Output:
Concept-25 Default Methods in Interfaces
➢ Before Java 8, interfaces could have only abstract methods. The implementation of these
methods has to be provided in a separate class.
➢ So, if a new method is to be added in an interface, then its implementation code has to be
provided in the class implementing the same interface.
➢ To overcome this issue, Java 8 has introduced the concept of default methods which allow the
interfaces to have methods with implementation without affecting the classes that implement
the interface. A default method should not override.
➢ A default method cannot be declared final.
Program:
Output:
Concept-26 Static Methods in Interface
➢ Similar to Default Method in Interface, the static method in an interface can be defined in the
interface, but cannot be overridden in Implementation Classes.
➢ To use a static method, Interface name should be instantiated with it, as it is a part of the
Interface only.
Program:
Output:
Important Question
1. Explain the concept of Inhibiting Inheritance of Class using final with a suitable example.
2. Write a Java Program to multiply two matrices.
3. Explain the concept of method overloading with an example.
4. Write a program to demonstrate the use of arrays as vectors.
5. What are the different methods of declaration and initialization of arrays in Java?
6. How are the elements of multidimensional arrays initialized?
7. How to assign a complete array to another array?
8. What do you understand by arrays of varying length?
9. How do you use for-each and determination of array size for accessing array elements and
displaying them on screen?
10. What are the different methods of sorting arrays in java?
11. Explain the concept of binary search for sorted arrays?
12. Explain the methods of searching a value in unsorted arrays?
13. What do you understand by dynamic change in length of an array?
14. Explain the concept of Array class in Java?
15. What do you understand by Inheritance and explain the benefits of inheritance?
16. Explain the types of inheritance with a suitable example programs?
17. What is an abstract class with a suitable example programs?
18. What is the different between an interface and abstract class?
19. Explain the concept of Universal Super Class-Object Class?
20. Explain the concept of Application of Keyword Super?
21. Explain about Dynamic Method Dispatch or Runtime Polymorphism?
22. Compare about method overloading and method overriding?
23. Different between a class and an interface?
24. Write about functional interface?
25. Explain about declaration and implementation of interface?
26. Does an interface extends another interface?
27. Explain about default method in an interface?
28. Explain about static method in an interface
29. Explain about nested interface in java?
30. How do you implement multiple inheritances using interface?
UNIT-4
Packages and Java Library: Introduction, Defining Package, Importing Packages and Classes
into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang Package
and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and
Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class, Time
Package, Class Instant (java.time.Instant), Formatting for Date/Time in Java, Temporal
Adjusters Class.
Exception Handling: Introduction, Hierarchy of Standard Exception Classes, Keywords
throws and throw, try, catch, and finally Blocks, Multiple Catch Clauses, Class Throwable,
Unchecked Exceptions, Checked Exceptions, try-with-resources, Catching Subclass Exception,
Custom Exceptions, Nested try and catch Blocks, Rethrowing Exception, Throws Clause.
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime
errors so that normal flow of the application can be maintained.
In other words, an exception is a run-time error. Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code.
Java exception handling is managed via five keywords:
try, catch, and finally, throw, throws
Program statements that you want to monitor for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown. Your code can catch this exception
(using catch) and handle it in some rational manner.
System-generated exceptions are automatically thrown by the Java run-time system.
An exception can occur for many different reasons.
Following are some scenarios where an exception occurs.
Output:-
The exception is caught by the default handler provided by the Java run-time system. Any exception
that is not caught by your program will ultimately be processed by the default handler. The default
handler displays a string describing the exception and terminates the program.
Checked Subclasses
Concept-3 Keywords throws and throw, try, catch, and finally Blocks
Syntax
Here, ExceptionType is the type of exception that has
occurred
try block
The default exception handler provided by the Java run-time system is useful for Debugging,
to handle an exception yourself it provides two benefits First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
It handle a run-time error, simply enclose the code that you want to monitor inside a try
block Immediately following the try block, include a catch clause that specifies the exception
type that you wish to catch. Java try block must be followed by either catch or finally
block.
catch block/clause
Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception (i.e., Exception)
OR the generated exception type. The catch block must be used after the try block only. You
can use multiple catch block with a single try block.
Program: Output
finally block:
Java finally block is a block that is used to execute important code such as closing
connection, stream etc. Java finally block is always executed whether exception is handled or
not. Java finally block follows try or catch block. The finally clause is optional.
Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Program
Output:
throw:-
The throw keyword is used to explicitly throw a single exception.
The keyword throw is used to throw an exception objects within a method.
We can throw either checked or unchecked exception in java by throw keyword.
When an exception is thrown, the flow of program execution transfers from the try block to
the catch block. Syntax:- throw exceptionobject;
We use the throw keyword within a method.
Program
Output:-
throws:-
The throws keyword in Java is used to declare exceptions that can occur during the execution
of a program.
For any method that can throw exceptions, it is mandatory to use the throws keyword to list
the exceptions that can be thrown.
The throws keyword provides information about the exceptions to the programmer as well as
to the caller of the method that throws the exceptions.
Syntax:
Program:
Output:
Output:
Output:
2) import package.classname;
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
The eight classes of java.lang package are known as wrapper classes in java.
Methods of Wrapper Classes
1. equals()
2. byteValue()
3. compareTo(type Object)
4. doubleValue()
5. floatValue()
6. intValue()
7. longValue()
8. ShortValue()
9. toHexString(type number)
10. valueOf(type number)
11. valueOf(String str)
12. toString(type number)
Program:
Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
It is used to round of the decimal numbers to the
Math.round()
nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
It returns the value of first argument raised to the
Math.pow()
power to second argument
It is used to find the largest integer value which is less
Math.floor() than or equal to the argument and is equal to the
mathematical integer of a double value.
It is used to find the smallest integer value that is
Math.ceil() greater than or equal to the argument or mathematical
integer.
Math.log() It returns the natural logarithm of a double value.
It is used to return the base 10 logarithm of
Math.log10()
a double value.
It is used to return the trigonometric Sine value of a
Math.sin()
Given double value.
It is used to return the trigonometric Cosine value of a
Math.cos()
Given double value.
It is used to return the trigonometric Tangent value of a
Math.tan()
Given double value.
It is used to return the trigonometric Arc Sine value of
Math.asin()
a Given double value
It is used to return the trigonometric Arc Tangent value
Math.atan()
of a Given double value.
It is used to return the trigonometric Hyperbolic
Math.sinh()
Cosine value of a Given double value.
It is used to return the trigonometric Hyperbolic Sine
Math.cosh()
value of a Given double value.
It is used to return the trigonometric Hyperbolic
Math.tanh()
Tangent value of a Given double value.
Program
Output:
Multithreaded Programming
Concept-1 Introduction
The process of executing multiple threads simultaneously is known as multithreading.
Thread is a lightweight unit of a process that executes in multithreading environment.
A program can be divided into a number of small processes.
Each small process can be addressed as a single thread (a lightweight process).
Multithreaded programs contain two or more threads that can run concurrently and each thread
defines a separate path of execution.
This means that a single program can perform two or more tasks simultaneously.
For example, one thread is writing content on a file at the same time another thread is
performing spelling check.
Process is the execution of a program that performs the actions specified in that program.
When program is loaded into the memory it automatically converting in to the process.
JAVA every program that we have been writing has at least one thread that is the MAIN
thread.
A Program starts executing the JVM is responsible for creating the main thread and calling the
main() Method.
Threads are executed by the processor according to the scheduling done by the java runtime
system by priority to every thread.
It simply means the higher priority as given preference for getting executed over the threads
having lower priority.
Advantage of Multithreading
Multithreading reduces the CPU idle time that increase overall performance of the system.
Since thread is lightweight process then it takes less memory.
Switching as well that helps to share the memory and reduce time of switching between
threads.
Multitasking
Multitasking is a process of performing multiple tasks simultaneously.
Computer system that perform multiple tasks like: writing data to a file, playing music,
downloading file from remote server at the same time.
Multitasking can be achieved either by using multiprocessing or multithreading.
Multitasking by using multiprocessing involves multiple processes to execute multiple tasks
simultaneously whereas Multithreading involves multiple threads to execute multiple tasks.
Thread vs Process
Parameter Process Thread
Definition Process means a program is in execution. Thread means a segment of a process.
Lightweight The process is not Lightweight. Threads are Lightweight.
Termination
The process takes more time to terminate. The thread takes less time to terminate.
time
Creation time It takes more time for creation. It takes less time for creation.
Communication between threads
Communication between processes needs
Communication requires less time compared to
more time compared to thread.
processes.
Context
It takes more time for context switching. It takes less time for context switching.
switching time
Resource Process consumes more resources. Thread consumes fewer resources.
Memory The process is mostly isolated. Threads share memory.
Sharing It does not share data Threads share data with each other.
Concept-2 Need for Multiple Threads & Multithreaded Programming for Multi-core Processor
To increase in throughput of computer is possible only by dividing the program into segments that are data
dependent and can be processed simultaneously by more than one processor. Thus, it decreases the total time
of computation.
This is the basis on which supercomputers are built.
In a supercomputer, thousands of processors are employed to concurrently process the data.
Hardware developers have gone a step further by placing more than one core processor in the same CPU chip.
Thus, now, we have multi-core CPUs.
Multithreaded Programming for Multi-core Processor
A CPU may have two cores - dual core or four cores - quad, six cores, or more.
CPUs having as many as 50 cores have also been developed. Moreover, computers with multi-core CPU are
affordable and have become part of common man's desktop computer.
Advancements in hardware are forcing the development of suitable software for optimal utilization of the
processor capacity. Multithread processing is the solution.
Multithread programming is inbuilt in Java and CPU capacity utilization may be improved by having multiple
threads that concurrently execute different parts of a program.
Concept-3 Thread life cycle or Thread States
Define a Thread:
Thread is a lightweight unit of a small process that executes in multithreading environment.
A program can be divided into a number of small processes.
Each small process can be addressed as a single thread (a lightweight process).
When program is load in to the main memory it is automatically converted as process.
Thread has its life cycle that includes various phases like: new, running, runnable, blocked, terminated etc.
Thread life cycle
New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on
it.
Runnable: After invocation of start() method on new thread, the thread becomes runnable.
Running: A thread is in running state if the thread scheduler has selected it.
Waiting: A thread is in waiting state if it waits for another thread to perform a task. In this stage the thread is
still alive.
Terminated: A thread enter the terminated state when it complete its task.
Daemon Thread
Daemon threads are a low priority thread that provides supports to user threads.
These threads can be user defined and system defined as well.
Garbage collection thread is one of the system generated daemon thread that runs in background.
These threads run in the background to perform tasks such as garbage collection.
Daemon thread does allow JVM from existing until all the threads finish their execution.
Concept-4 Creation of New Threads
Create a thread by instantiating or creating an object of type Thread class.
Java defines two ways in which this can be accomplished
1. By implementing the Runnable interface.
2. By extending the Thread class.
By extending the Thread class
This is the way to create a thread by a new class that extends Thread class and create an instance of
that class.
The extending class must override run() method which is the entry point of new thread.
Create the thread object and use the start() method to initiate the thread execution.
Declaring a class: Any new class can be declared to extends the thread class, thus inheriting all the
functionalities of the Thread class.
Class NewThread extends Thread {
------
------
}
Overriding the run() Method: The run() Method has to be overridden by writing codes required for the
thread. Specify the code that your thread will execute inside run() method.
Starting New Thread: The Start() Method which is required to create and initiate an instance of our Thread
class. NewThread thread1=new NewThread();
thread1.start();
The first line creates an instance of the class NewThread, where the object is just created. The thread is in
newborn state.
Second line which calls the start() method, moves the thread to runnable state, where the JVM will schedule
the thread to run by invoking the run() method. Now the thread is said to be in running state.
Program:
Methods Description
static Thread currentThread() Returns a reference to the currently executing thread
static int activeCount() Returns the current number of active threads
long getID() Returns the identification of thread
final String getName() Returns the thread’s name
final void join() Wait for a thread to terminate
void run() Entry point for the thread
final void setDaemon(boolean how) If how is true, the invoking thread is set to daemon status.
final boolean isDaemon() Returns true if the invoking thread is a daemon thread
final boolean isAlive() Returns boolean value stating whether a thread is still running
void interrupt() Interrupts a thread
Thread.State getState() Returns the current state of the thread
final int getPriority() Returns the priority of the thread
static boolean interrupted() Returns true if the invoking thread has been interrupted
final void setName(String thrdName) Sets a thread’s name to thrdName.
final void setPriority(int newPriority) Sets a thread’s priority to new priority
static void sleep(long milliseconds) Suspend a threads for a specified period of milliseconds
void start() Start a thread by calling its run() Method.
void destroy() Destroy the thread
Cause the current executing thread to pause and allow the other
static void yield()
threads to execute
Constructors of Thread Class
Constructors Description
It has no arguments, which simply means it uses the default name
Thread()
and the thread group
Thread(String threadName) The name of the thread can be specified as in threadName
Thread(ThreadGroup threadGroup,
Can specify the thread group and thread name.
String threadName)
Thread(Runnable threadOb, String ThreadOb is an instance of a class that implements the Runnable
threadName) interface.
By implementing the Runnable interface
Java Runnable is an interface used to execute code on a concurrent thread.
It is an interface which is implemented by any class, that the instances of that class should be executed by a
thread class.
The Runnable interface has an undefined method run() with void as return type, and it takes in no arguments.
This interface is present in java.lang package.
Method Description
This method takes in no arguments. When the object of a class implementing Runnable
public void run() interface is used to create a thread, then the run method is invoked in the thread which
executes separately.
Runnable interface is when we want only to override the run method.
When a thread is started by the object of any class which is implementing Runnable, then it invokes the run
method in the separately executing thread.
The class that implements Runnable, you will instantiate an object of type Thread from that class.
Thread defines several constructors
Thread(Runnable threadOb, String threadName)
ThreadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin.
The name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start() method, which is declared
within Thread class.
Program:
Concept-5 Thread Priority
Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
higher-priority threads get more CPU time than lower-priority threads.
A higher-priority thread can also preempt a lower-priority one when a lower-priority thread is running and a
higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower-
priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a method of Thread class.
This is its general form: final void setPriority(int level)
level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
These priorities are defined as static final variables within Thread class.
To obtain the current priority setting by calling the getPriority( ) method of Thread final int getPriority( ).
Program:
Concept-6 Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
The synchronization is mainly used to
1. To prevent thread interference. 2. To prevent inconsistency problem.
Synchronization is built around an internal entity known as the lock or monitor.
Every object has a lock associated with it.
There are two types of thread synchronization
1. Synchronized method. 2. Synchronized block.
Synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.
Program: Output
Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use
synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Program: Output
Concept-7 Inter-thread Communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
Inter-thread communication is a mechanism in which a thread gets into wait state until another thread sends a
notification.
It is implemented by following methods
wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened.
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Concept-8 String Handling in Java: Introduction & String Class
A String is a sequence of character such as “abcdef” or “bell”.
In Java, a String is an object representing a sequence of characters.
In Java, a string is an object of a class, and there is no automatic appending of null character
by the system.
In Java, there are three classes that we can create strings and process them with methods.
(i) class String (ii) class StringBuffer (iii) class StringBuilder
All the three classes are part of java.lang package.
All the three classes have several constructors that can be used for constructing strings.
In the case of String class, an object may be created as String str1 = "abcd";
Here: String is a Predefined class of java.lang package str1 is an object not a variable. "abcd" is string literal
Program:
Output:
Output:
Concept-10 Methods for Extracting Characters from Strings
Method Description
char charAt(int index) It is used to extract a single character at an index
void getChars(int stringStart, int
It is used to extract more than one character
stringEnd, char arr[], int arrStart)
It is used extract characters from String object and then convert the
byte [] getBytes()
characters in a byte array
It is used to convert all the characters in a String object into an array of
char [] toCharArray()
characters.
int length() It is used extract the length of the string
Program:
Output:
Output:
Concept-13 Methods for Searching Strings
Method Description
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int
Returns the index within this string of the first occurrence of the specified character,
fromIndex) starting the search at the specified index.
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str,
Returns the index within this string of the first occurrence of the specified substring,
int fromIndex) starting at the specified index.
Program:
Output: