0% found this document useful (0 votes)
25 views183 pages

All Units

This document provides an overview of Java programming, covering its structure, data types, variables, operators, control statements, and user input methods. It details Java's history, features, and applications, as well as how to write simple Java programs and handle command line arguments. Additionally, it explains variable types, scopes, and naming conventions in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views183 pages

All Units

This document provides an overview of Java programming, covering its structure, data types, variables, operators, control statements, and user input methods. It details Java's history, features, and applications, as well as how to write simple Java programs and handle command line arguments. Additionally, it explains variable types, scopes, and naming conventions in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 183

UNIT-1

Program Structure in Java

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.

Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions,


Ternary Operator?:, Switch Statement, Iteration Statements, while Expression, do–while Loop,
for Loop, Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.

Conpect-1 Introduction to JAVA


a) History of JAVA
 JAVA is a high-level, general-purpose, object-oriented, and secure programming language
developed by James Gosling at Sun Microsystems, Inc. in 1991.
 It is formally known as OAK. In 1995, Sun Microsystems changed the name to JAVA.
 In 2009, Sun Microsystems takeover by ORACLE Corporation.
 Initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was suited for internet programming.
 Currently, Java is used in internet programming, mobile devices, games, e-business
solutions, etc.
 The history of java starts from Green Team.
 Java team members (also known as Green Team).
Why "Oak" name
 Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
 There are 3 types’ editions in JAVA: Each edition of Java has different capabilities.
 Java Standard Editions (J2SE): It is used to create programs for a desktop computer.
 Java Enterprise Edition (J2EE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
 Java Micro Edition (J2ME): It is used to develop applications for small devices such as
set-top boxes, phone, and appliances.
b) Applications of JAVA

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in
3. Enterprise Applications such as banking applications.
4. Mobile Application
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
c) Java features
 The features of Java are also known as java buzzwords.
 A list of most important features of Java language is given below.
1. Simple 2. Object-Oriented 3. Portable 4. Platform independent

5. Secured 6. Robust 7. Architecture neutral 8. Interpreted

9. High Performance 10. Multithreaded 11. Distributed 12. Dynamic


1. Simple:-
Java is a simple language because its syntax is simple, clean, and easy to understand. Complex
and ambiguous concepts of C++ are either eliminated or re-implemented in Java. For example,
pointer and operator overloading are not used in Java.
2. Object-oriented:-
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation
3. Platform Independent:-
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language. On
compilation Java program is compiled into byte code. This byte code is platform independent
and can be run on any machine, plus this byte code format also provides security. Any machine
with Java Runtime Environment can run Java Programs.

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

Documentation Section: Documentation Section consists of a set of comment lines giving


name of the program, author name and other details optionally which programmer like to use
later. These comment lines are optional Ignored by compiler during program execution.
Ex: /* Addition of 2 numbers in java */
Package statement: Package statement placed just after documentation section. In this section
we can declare user defined packages this is optional section and note that there is only one
package statement in java program
Ex: package rc;
Import Statements: A package may contain many predefined classes and interfaces. If we
want to use any of them in our program we need to import that class. It is also optional
Ex: import java.util.Scanner; or import java.util.*;
Interface Statements: A java program may contain interfaces are used to achieve 100%
abstraction in java. It is also optional
Ex: interface Interface1 {
}
Class without main () method: This contains instance variables and methods in it. We can
also write main() method here. (then there is no need of class with main() section)
class Sample {
int s,b; // instance variables
void fun() //methods
{
int x,y; // local variable
}
}
Class with main() method: This section is mandatory because it contain main() method. Every
java program’s execution starts from main function only. Its Essential
Ex: class Mainclass
{
public static void main(String args[])
{
……
}
}
Concept-3 User Input to Programs
 Java Scanner class allows the user to take input from the console. It belongs
to java.util package.
 Java Scanner class is a text scanner that breaks the input into tokens using a delimiter. The
delimiter is whitespace by default.
 It is used to read the input of primitive types like int, double, long, short, float, and byte.
 Importing the class is the first step.
import java.util.Scanner;
 The object of the class Scanner is declared as follows.
Scanner sc= new Scanner (System. in);
Methods of Java Scanner Class
Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.

Example Program: - Illustration of a user's input from keyboard into program


Output:-

Concept-4 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.
 When a Java application is invoked, the runtime system passes the command line arguments
to the application's main method through an array of strings.
 It must be noted that the number of arguments in an array. To ensure this, we can make use
of the length property of the array.
Example Program:- Illustration Concept of the Command Line Arguments

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:-

Concept-5 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,
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

 The float data type is a 32-bit floating point. That is 4 byte


 Its value range is 1.4 e-45 to 3.4e+38
 This is used for single-precision floating point number that is 7 digits after the decimal point
 The float data type should never be used for precise values, such as currency.
 Its default value is 0.0F. Example: float f1 = 234.5f
Double Data Type
 The double data type is a 64-bit floating point. That is 8 byte.
 Its value range is 4.9e-324 to 1.8e+308
 This is used for double-precision floating point number that is 15 digits after the
decimal point.
 The double data type also should never be used for precise values, such as currency.
 Its default value is 0.0.
Example: double d1 = 12.3.
Char Data Type
 The char data type is a single 16-bit Unicode character. That is 2 byte.
 Its value-range lies between '\u0000’ (or 0) to '\uffff'.
 The char data type is used to store characters.
Example: char letterA = 'A'
Concept-6 Declaration of Variables
 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 is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be changed.
 All variable must be declared before they can be used in java.
 A variable is defined by the combination of an variable name, a type, and an optional
initializer.

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:

Java variable naming rules


 All variable should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 Variable can never used special character like +,-,&,*.
 Space are not allowed in variable names.
 A keyword cannot be used as an variable name.
 Most importantly, variable are case sensitive. Such as ADD or add both are different.
 After the first character, variable can have any combination of characters.
Concept-6 Scope of Variable Identifier
 The scope and lifetime of a variable is the part of the program in which it is visible and holds
the last entered value.
 A variable can be declared and defined inside a class, method, or block. It defines the scope
of the variable i.e. the visibility or accessibility of a variable.
 In Java, there are distinctly two types of scopes. (a) class scope and (b) method scope
 A variable declared in a class has class scope and scope of a variable declared in a method
has method scope.
 The variables declared in a block have block scope.
 Variable declared inside a block or methods are not visible to outside.
 Thus, the variables defined in main() at the beginning have scope in entire main() method,
however, those defined in a block have block scope.
 A block starts with the left brace ({ ) and ends with the right brace ( }).
The scope of variables is governed by the following rules.
 The scope starts from the point the variable is defined in the block (declared and value
assigned to it).
 Although the variable may be defined anywhere in a block, it can be used only in the
statements appearing after its definition Therefore, there is no use in defining a variable at
the end of block.
 If there are nested blocks, a variable defined in the outer block is visible in the inner blocks
also and it cannot be redefined with the same name in the inner blocks.
Programs
Output:-

Concept-7 Introduction to Operators


 Operators are special symbols (characters) that carry out operations on operands such as
(variables and values). For example: +, -, *, /, < , >, ?: etc.
 If an operator takes only one operand for its operation it is called unary operator.
 If it takes two operands, it is called binary operator and if it takes three operands, it is called
ternary operator.
There are many types of operators in Java which are given below:
1. Assignment Operator
2. Compound Assignment Operator
3. Arithmetic Operator
4. Increment & decrement Operator
5. Relational Operator
6. Ternary Operator
7. Boolean Logical Operator
8. Bitwise Operator & Bit Shift Operators
9. Special operators
Assignment Operator ( = ) & Compound Assignment Operator:-
 The Assignment operator is the single equal sign “=”.
 To assign the value 10 to a variable called X Example:- X=10;
 We write the name of the variable to which a value is to be assigned, and on its right, we
write the value to be assigned
 The name or variable on the left is also called L-value and the values on the right of = is
called R-value. Therefore, R-value is assigned to L-value.
variable_name = Expression;
Syntax: Datatype variable = value;

int x = 10;
Compound Assignment operators

Syntax: variable op=expression

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

Here String is class and


also act string data type.
Increment & decrement Operator (++) and (--):-
 In JAVA Increment & Decrement Operator ++ and -- operator as both prefix and postfix
in Java.
 The ++ operator increases value by 1 and -- operator decreases the value by 1
X=X+1 (Or) X++; Y=Y+1 (Or) ++Y;
X=X-1 (Or) X--; Y=Y-1 (Or) --Y;
 There is no blank space between the composite symbols ++ or –

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:-

Boolean Logical Operators


 A Boolean variable can have one of the two values, that is true or false.
 Logical Operators operate only on boolean values.
 The logical operators combine two boolean values to form a resultant boolean values.
Truth Table

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.

Program on Bitwise NOT


Bitwise XOR
 Bitwise XOR is a binary operator (operates on two operands).
 It's denoted by ^.
 The ^ operator compares corresponding bits of two operands.
 If corresponding bits are different, it gives 1. If corresponding bits are same, it gives 0.

Program on Bitwise XOR


Bit Shift Operators
 A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left.

 Bit shift Operators are as follows


1. Left Shift (<<) 2. Right Shift (>>)
Left Shift Operators
 The left shift operators (<<) shifts all of the bits in a value to the left a specified number of
times. Syntax :- value << num
 Here, num specifies the number of positions to left -shift the value in value.
 (<<) moves all of the bits in the specified values to the left by the number of bits positions
specified by num.
 When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end.

Right Shift Operators


 The Right shift operators (>>) shifts all of the bits in a value to the right a specified number
of times. Syntax: - value >> num
Here, num specifies the number of positions to right - shift the value in value.
 (>>) moves all of the bits in the specified values to the right by the number of bits positions
specified by num.
 When shifting right with a right shift, the least-significant bit is lost and a 0 is inserted on
the other end.

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:-

Concept-8 Precedence and Associativity of Operators


 Operator precedence determines the order in which the operators in an expression are
evaluated.
 Precedence and associativity are two features of Java operators.
 When there are two or more operators in an expression, the operator with the highest priority
will be executed first. Associativity specify the direction that is left to right or right to left.
Concept-9 Control Statements
 A control statement in java is a statement that determines whether the statements will be
executed or not.
 It controls the flow of a program.
 The Java control statements inside a program are usually executed sequentially.
 Sometimes a programmer wants to break the normal flow and jump to another statement or
execute a set of statements repeatedly control statements are used.
 Control statements in java which breaks the normal sequential flow of the program are called
control statements.

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

3. If else if ladder 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

For Each Loop


 The for-each loop is used to traverse array in java.
 It is easier to use than simple for loop because we don't need to increment value and use
subscript notation.
 It works on elements basis not index.
 It returns element one by one in the defined variable.
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.

There are two types of type casting. They are,


i. Implicit Type casting ii. Explicit Type casting
Implicit Type casting or 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.
 Implicit type casting is done automatically by a compiler when we assign a value to the
variable.
 It is safe because there is no chance to lose data.
byte -> short -> char -> int -> long -> float -> double
 Example:
int a=10; double b;
b=a;
 Here a is integer and b is double variables.
 Integer value is automatically converted into double by the compiler.
Explicit Type casting OR Narrowing Type Casting
 Converting a higher data type into a lower one is called narrowing type casting.
 It is also known as explicit conversion or casting up.
 It is done manually by the programmer. In this conversion, there is loss of data.
 The explicit type casting is carried out by the following code:
type variable = (new_type) variable;
double D = 6.865;
int A = (int) D;
double -> float -> long -> int -> char -> short -> byte
Program on Implicit Type casting

Program on Explicit Type casting


Concept-12 Static Variables and Methods
Static Variables
 The static variables are class variables. Only one copy of such variables is kept in the
memory and all the objects share that copy.
 The static variables are accessed through class reference, whereas the instance variables are
accessed through class object reference
 The variables in a class may be modified by modifier static.
 The non-static variables declared in a class are instance variables.
 A static variable can be accessed directly by the class name and doesn’t need any object.
Syntax <class-name>.<variable-name>

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.

Concept-1 Classes and Objects: Introduction


Classes:
 In object-oriented programming technique, we design a program using objects and classes.
 A class is a group of objects which have common properties.
 It is a template or blueprint from which objects are created.
 It is a logical entity. It can't be physical.
 Classes are user-defined data type.
 Very simple class may contain only code and only data (Data member & methods).
 A class is declared by use of the class keyword.
 A class in Java can contain: 1. Fields 2. Methods 3. Constructors 4. Blocks 5. Nested
class and interface.
 The data and variables, defined within a class are called instance variables.
 Instance variable doesn't get memory at compile time.
 It gets memory at runtime when an object or instance is created.
 The code is contained within methods, the methods and variables defined within a class are
called members of the class.
Objects:
 An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
 An object is a real-world entity. An object is a runtime entity.
 An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc.
 The object is an instance of a class.
An object has three characteristics
State: Represents the data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each
object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
Concept-2 Class Declaration and Modifiers
Class Declaration
 A class declaration starts with the Access modifier. It is followed by keyword class, which is
followed by the class name or identifier.
 The body of class is enclosed between a pair of braces { }.
Syntax:

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();

Name of the object Class name or constructor name

 The object is created as follows

 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:-

Area of myFarm = 800.0


Concept-5 Assigning One Object to Another
 When one object of a class provides a reference to another object of the same class, the first
object can access the second object’s data and methods.
 Java provides the facility to assign one object to another object all the properties of
old_object will be copied to new object.
Syntax: new_Object = old_object;
 The Following is the example as follows
farm2=farm1;
Here farm2 and farm1 are the objects of the same class Farm.
Program:-

Output:-

Area of form1= 800.0


Area of form2 = 800.0
Concept-6 Access Control for Class Members
 An access modifier in java specifies accessibility (scope) of instance variables, methods,
classes, constructor etc.
 In Java, There are three access specifiers are permitted:
1. public 2. protected 3. private 4. default or No modifier
private: private has scope within the class only
public: public has scope useful to every where
protected: protected has scope within the package and, child class of same package and child
class of other package
Default or No modifier: if you don’t use any modifier it is treated as default it is accessible
only within the package.
The coding with access specifiers for variables is illustrated as
access_specifier type identifier;
Examples: int n; //No access specifier
public int m; //public access.
protected int k; //protected
private int p; //private – access only to class members
Concept-7 Accessing Private Members of Class
 Private members of a class, whether they are instance variables or methods, can only be
accessed by other members of the same class.
 Any outside code cannot directly access them because they are private. However, interface
public method members may be defined to access the private members.
 The code other than class members can access the interface public members that pass on the
values.
Program:-
Output:-

Concept-8 Constructor Methods for Class


 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new keyword, at least one constructor is called.
 A constructor is a block of codes similar to the method. It is called when an instance of the
class is created.
 At the time of calling constructor, memory for the object is allocated in the memory.
 It calls a default constructor if there is no constructor available in the class.
 In such case, Java compiler provides a default constructor by default.
Rules for creating Java constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no return type
3. A Java constructor cannot be abstract, static, final, and synchronized
4. Constructor cannot be inherited
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor
 A constructor is called "Default Constructor" when it doesn't have any parameter.
 The default constructor provided by java compiler, is a no-argument constructor with empty
body.
 The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
 If there is no constructor in a class, compiler automatically creates a default constructor.
Syntax of default constructor

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:-

Concept-11 Keyword this


 this keyword in Java is a reference variable that refers to the current object of a method or a
constructor.
 this keyword in Java is to remove the confusion between class variable and parameters that
have same names.
Following are various uses of ‘this’ keyword in Java
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.
Program:
Output:-

Concept-12 Nested Classes


 The Java programming language allows you to define a class within another class. Such a
class is called a nested class.
 Non-static nested classes (inner classes) have access to other members of the enclosing class,
even if they are declared private.
 We need to take support of outer class to access inner class.
Program:
Concept-11 Methods: Introduction & Defining Methods
Methods in JAVA
 Method is a way to perform some task.
 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.
 The method in Java is a collection of instructions that performs a specific task.
 It provides the reusability of code.
 Can also easily modify code using methods.
 What is a method in Java?
Return type of methods, method declaration, and how to call a method in Java
 Write a method once and use it many times. Do not require to write code again and again.
 It also provides the easy modification and readability of code.
 The method is executed only when we call or invoke it.
 In Java, a method must be defined inside a class and an interface.
 The most important method in Java is the main() method.
 The main() is the starting point for JVM to start execution of a Java program.
 Without the main() method, JVM will not execute the program.
Method Declaration
 The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments (Parameter List).
 It has six components that are known as method Declaration.
Method Signature
 Every method has a method signature. It is a part of the method declaration. It includes the
method name and parameter list.
a) 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 Program.
Program
Private: When
hen 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.
b) Return Type: Return type is a data type
type that the method returns. It may have a primitive
data type, etc. If the method does not return anything, we use void keyword.
c) 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.
If we are creating a method for subtraction of two numbers, the method name must be
subtraction(). A method is invoked by its name.
d) 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.
c) 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, the method name must be a verb and start with a lowercase letter.
 If the method name has more than two words, the first name must be a verb followed by
adjective or noun.
 In the multi-word method name, the first letter of each word must be in uppercase except the
first word. For
Example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
Program:-
Concept-12 Overloaded Methods
 If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
 Method Overloading is one way of achieving polymorphism in JAVA.
 If we have to perform only one operation, having same name of the methods but different in
parameters is increases the readability of the program.
Advantage of method overloading
 Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
 Method Overloading is not possible by changing the return type of the method only.
Method Overloading Changing no. of arguments
 In this Example, We have created two methods, first add() method performs addition of two
numbers and second add() method performs addition of three numbers.
 We are creating static methods so that we don't need to create instance for calling methods.
Program:-

Method overloading changing data type of arguments


 We have created two methods that differ in data type.
 The first add method receives two integer arguments and second add method receives two
double arguments.
Program:-

Concept-13 Overloaded Constructor Methods


 A constructor method is automatically called whenever a new object of the class is
constructed. It creates and initializes the Object.
 A constructor method has the same name as the name of class to which it belongs. It has no
type and it does not return any value. It only initializes the object.
 Constructor overloading in Java is a technique that enables a single class to have more
than one constructor that varies by the list of arguments passed.
 The constructor overloading enables the accomplishment of static polymorphism.
 Each overloaded constructor performs various tasks for specified purposes.
Program:-

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

2. Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
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).
Program:-

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.

Concept-1 Arrays: Introduction

➢ 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

Concept-2 Declaration and Initialization of Arrays


Declaration of Array
➢ The declaration starts with the type, followed by an identifier and square bracket, and ends
with a semicolon.

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

Concept-5 Assigning Array To Another Array


➢ In Java, one array may be assigned to another array of same data type.
➢ In Java, it will copy all the elements of one array into another array.
➢ In this process, the second array name contains the address is assigned to the first array.
➢ The second array is not a new array, it contain the reference of the first array.
➢ array1 is assigned to array2. Then, array1 is modified array2 also gets modified, array2 is not
show an independent array.
Program:-

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:

Concept-8 Search for Values in Arrays


➢ Searching in data-structure refers to the process of finding a desired element in set of items.
➢ Searching is divided into two types 1. Linear Search 2. Binary Search
Program:-
Concept-8 Two-dimensional Arrays
➢ A two-dimensional array is treated as an array of arrays, and each of these arrays may have a
different number of elements.
➢ For Example:- Matrices is the example for two-dimensional arrays.
➢ Array index start from 0th index not 1st index. And 2D array also start from 0th row and 0th
column index.

➢ A two dimensional array is declared as follows:


datatype identifier[][];
For Example:- int number[][];
➢ The number of square brackets indicates the dimension or depth of an array.
➢ The Memory allocation may be achieved by the operator new as:
datatype arrayname[][]=new datatype[rows size][column size]
For Example:- int number[][]=new int[3][2]
➢ In the above Example rows size is 3 and column size is 2 hence 3x2 Matrices is created.
Alternative array Declaration syntax:-
➢ Use of a square bracket before and after the identifier will create a multi dimensional array.
int [] number [];
➢ The above declaration is equivalent to
int [][] number; Or int number[][];
Declaration and initialization of array:-
➢ A two dimensional array may be declared and initialized as
int [][] number=new int[][] { {1,2,3}, { 4,5,6}} Or
int [][] number={{1,2,3},{4,5,6}}
Program:-

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.

➢ A three-dimensional array may be declared as


int tDArray [][][]; //Declaration double d3Array [][][]; //Declaration
Syntax: datatype identifier[][][]=new datatype[][][];
Example: int array[][][]=new int[2][3][3];
Program:-

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:-

Concept-12 Arrays as Vectors


➢ Similar to Arrays, vectors are another kind of data structure that is used for storing
information.
➢ Using vector, we can implement a dynamic array.
➢ It is found in the java.util package.
➢ Vector is like the dynamic array which can grow or shrink its size.
The following are the vector constructors:
Constructor name Description
Vector() creates a default vector having an initial size of 10.
Vector(int size) creates a vector whose initial capacity is specified by size.
creates a vector with initial capacity specified by size and increment
Vector(int size, int incr) is specified by incr. The increment is the number of elements added
in each reallocation cycle.

Example:- Vector vec = new Vector(5); // declaring with initial size of 5


Vector vew =new Vector(5,2);
Vectors have a number of advantages over arrays.
1. Vectors are dynamically allocated, and therefore, they provide efficient memory allocation.
2. Size of the vector can be changed as and when required.
3. They can store dynamic list of elements.
4. The element can be added or deleted from the list as per the requirement.
Some of the important methods of Vector class.
Method Description
add() It is used to append the specified element in the given vector.
clear() It is used to delete all of the elements from this vector.
capacity() It is used to get the current capacity of this vector.
firstElement() It is used to get the first component of the vector.
lastElement() It is used to get the last component of the vector.
sort() It is used to sort the list according to the order.
get() It is used to get an element at the specified position in the vector.
size() It is used to get the number of element in the given vector.

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

Concept-13 Types of Inheritances


The following types of inheritances are supported by Java.
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance using interfaces
➢ There can be three types of inheritance in java: single, multilevel and hierarchical.
➢ Multiple and hybrid inheritance is supported through interface only.
➢ JAVA does not Supported multiple inheritance & Hybrid inheritance using classes.
➢ We can achieve the multiple inheritance & Hybrid inheritance through the interface.
➢ Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.
The class A serves as a base class for the derived class B.
Program:

Output:-

➢ Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base


class and as well as the derived class also act as the base class to other class.
➢ The class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.
Program:

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:-

Concept-14 Universal Super Class-Object Class


➢ The Object class is the parent class of all the classes in java by default. In other words, it is
the topmost class of java.
➢ Every class in java is descended from the object class.
➢ It is available in the java.lang Package
➢ By default object class is inherited to our newly creating class.
Example of Object Class

public class Circle{ public class Circle extends object{

//Methods & Data members //Methods & Data members

} }
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;

Concept-16 Application of Keyword Super


➢ The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
➢ Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Program:-

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:

Dynamic Binding or Late Binding


➢ When compiler is not able to resolve the call/binding at compile time, such binding is
known as Dynamic or late Binding.
➢ Method Overriding is a perfect example of dynamic binding as in overriding both parent and
child classes have same method and in this case the type of the object determines which
method is to be executed.
➢ The type of object is determined at the run time so this is known as dynamic binding.
Program:

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

The relationship between classes and interfaces


➢ A class extends another class, an interface extends another interface, but a class implements an
interface.
➢ Interface fields are public, static and final by default, and the methods are public and
abstract.

Concept-21 Implementation of Interface


➢ Declaration of class that implements an interface

➢ If a class extends another class as well as implements interfaces, it is declared as

➢ A class implementing an interface must provide implementation for all its methods unless it is
an abstract class.
➢ Example:

class A implements C,D{ class A extends B implements C,D{


//Class Body // Class Body
} }
Program

Here Printable is the interface and it


contain the abstract methods

Here A6 is the class that implements the


printable interface
Output:
Hello
Concept-22 Multiple Interfaces
➢ Multiple interfaces can also be implemented in Java.
➢ For this, the class implements all the methods declared in all the interfaces.
➢ When the class is declared, names of all interfaces are listed after the keyword
implements and separated by comma.
➢ Multiple inheritance is not supported by java classes because of ambiguity or diamond
problem but it is available in java interfaces
➢ As for example, if class A implements interfaces C and D, it is defined as

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:

Concept-27 Functional Interfaces


➢ An Interface that contains exactly one abstract method is known as functional interface.
➢ It can have any number of default, static methods but can contain only one abstract method.
➢ Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces.
Program:
Different between the abstract class and interface in java
Abstract class Interface
Abstract class can have abstract and non Interface can have only abstract methods.
abstract methods. and it can have default and static methods also.
Abstract class doesn't support multiple
Interface supports multiple inheritances.
inheritances.
Abstract class can have final, non-final, static
Interface has only static and final variables.
and non-static variables.
Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
An abstract class can extend another Java An interface can extend another Java interface
class. only.
An abstract class can be extended using An interface can be implemented using
keyword "extends". keyword "implements".
A Java abstract class can have class members Members of a Java interface are public by
like private, protected, etc. default.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

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.

Concept-1 Exception Handling: Introduction

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

1. A user has entered an invalid data.


2. A file that needs to be opened cannot be found.
3. A network connection has been lost in the middle of communications or the JVM
has run out of memory.
Advantage of Exception Handling
 The core advantage of exception handling is to maintain the normal flow of the application.
 An exception normally disrupts the normal flow of the application that is why we use
exception handling.
Uncaught Exceptions Java run-time system detects the attempt to divide by zero. The
execution of Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler and deal with
immediately.

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.

Concept-2 Types of Java Exceptions


 There are mainly two types of exceptions: checked and unchecked.
Checked exceptions:- A checked exception is an exception that is checked by the compiler at
compilation- time, these are also called as compile time exceptions. These exceptions cannot
simply be ignored, the programmer should take care of (handle) these exceptions.
For Example:- ClassNotFoundException, NoSuchFieldException,
NoSuchMethodException etc;
Unchecked exceptions:- An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at
the time of compilation.
For Example:- ArithmeticException, ArrayIndexOutOfBoundsException,
NullPointerException, NegativeArraySizeException etc;
Unchecked Subclasses

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:

Concept-4 Multiple Catch Clauses


 More than one exception could be raised by a single piece of code. To handle this type of
situation, you can specify two or more catch clauses, each catching a different type of
exception.
 When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed.
 After one catch statement executes, the others are bypassed, and execution continues after
the try/catch block.
Program:

Output:

Concept-5 Hierarchy of Standard Exception


 In Java, exceptions are instances of classes derived from the class Throwable which in turn is
derived from class Object.
 Whenever an exception is thrown, it implies that an object is thrown.
 Only objects belonging to class that is derived from class Throwable can be thrown as
exceptions.
 The next level of derived classes comprises two classes: the class Error and class Exception.
 Error class involves errors that are mainly caused by the environment in which an application
is running.
 All errors in Java happen during runtime.
Examples:
 OutOfMemoryError occurs when the JVM runs out of memory and StackOverflowError
occurs when the stack overflows.
 Exception class represents exceptions that are mainly caused by the application itself.
 It is not possible to recover from an error using try–catch blocks.
 The only option available is to terminate the execution of the program and recover from
exceptions using either the try–catch block or throwing an exception. •
 The exception class has several subclasses that deal with the exceptions that are caught and
dealt with by the user’s program.
 The Error class includes such errors over which a programmer has less control.
 A programmer cannot do anything about these errors except to get the error message and
check the program code.
 A programmer can have control over the exceptions (errors) defined by several subclasses of
class Exception.
 The subclasses of Exception class are broadly subdivided into two categories.
 Unchecked exceptions These are subclasses of class RuntimeException, derived from
Exception class. For these exceptions, the compiler does not check whether the method that
throws these exceptions has provided any exception handler code or not.
 Checked exceptions These are direct subclasses of the Exception class and are not subclasses
of the class RuntimeException. These are called so because the compiler ensures (checks) that
the methods that throw checked exceptions deal with them.
Concept-6 try-with-resources
 In Java, the try-with-resources statement is a try statement that declares one or more resources
 The resource is as an object that must be closed after finishing the program.
 The try-with-resources statement ensures that each resource is closed at the end of the
statement execution.
 You can pass any object that implements java.lang.AutoCloseable
Program: Output:

Concept-7 Nested try and catch Blocks


 The try block within a try block is known as nested try block in java.
 Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
 If no catch block matches, then the Java runtime system handles the exception.
Program:

Output:

Concept:-8 Catching Subclass Exception


 A method in super class. When this method is overridden in subclass with exception handling,
then there are some points that need to be taken into consideration.
 If the super class method does not declare any exception, then subclass overridden method
cannot declare checked exceptions but it can declared unchecked exceptions.
Program: Subclass overridden method declaring checked exception

Output:

Program: Subclass overridden method declaring unchecked exception


Output:

Concept:-9 Custom Exceptions


 It is also called as user defined exception.
 A programmer may create his/her own exception class by extending the exception class and
can customize the exception according to his/her needs.
 Using Java custom exception, the programmer can write their own exceptions and messages.
1. Extend the Exception class as
class UserException extends Exception
{
// Statements
}
2. Define constructor of user exception class and this constructor takes a string argument
3. Write the code for the class containing the main class. The try catch block is written within
this class.
Program:
Output:

Concept:-10 Introduction, Defining Package


 A java package is a group of similar types of classes, interfaces and sub-packages.
 A Package can be defined as a collection used for grouping a variety of classes and interface
based on their functionality
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection & removes naming collision.
 This means that a unique name had to be used for each class to avoid name collision
 Package in java can be categorized in two form, built-in package or API and user-defined
package.
 There are many built-in packages such as java, lang, net, io, util, sql etc.
 The related classes are put the into one packages.
 After that, we can simply write an import class from existing packages and use it in our
program.
 A package is a container of a group of related classes.
Built-in Packages
These packages consist of a large number of classes which are a part of Java API. Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes (e.g classes which defines primitive
data types, math operations). This package is automatically imported.
2) java.io: Contains classes for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user.
 A package declaration resides at the top of a java source file. All class are to be placed in a
package have common package name.
 The name of the package should be followed by the keyword package, declared at the top of
the program. Thus, we can define a class belonging to a package.
Syntax of package
package <package_name>
Example of package package college;
 While declaring the package every character must be in lower case.
 The source file allow to declared only one package and it must be the first statement in a
JAVA source file
 The Package statement defines a name space in which classes are stored.
 If omit the package statement, the class name are put into the default package, which has no
name.
Concept:-11 Importing Packages and Classes into Programs
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) import package.*;
 If you use package.* then all the classes and interfaces of this package will be accessible.
 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.*

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

3) 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. Example of package by import fully qualified name
Concept:-12 Wrapper Classes and Auto-boxing and Auto-unboxing
 The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
 The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into
corresponding objects.
 Autoboxing and Unboxing are the features included in Java 1.5
 Autoboxing and Unboxing feature convert primitives into objects and objects into primitives
automatically.
 The automatic conversion of primitive into object is known as Autoboxing and vice-versa
Unboxing.
Auto Boxing or Boxing:
1. Autoboxing is the process of converting a primitive type data into its corresponding wrapper
class object instance
2. Done dynamically
Unboxing:
1. Unboxing is the process of converting a wrapper instance into a primitive type
2. Done automatically

 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:

Concept:-13 Access Control


Concept:-14 class Math
 Java Math Class in Java contains certain methods to perform different numeric operations, is
exponential, square root, logarithmic, trigonometric functions.
 Java Math class provides several methods to work on math calculations like min(),
max(),avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
 Arithmetic operations like increment, decrement, divide, absolute value, It should be checked
against the maximum and minimum value as appropriate.

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:

Concept:-15 Java util Classes and Interfaces


Concept:-16 Temporal Adjusters Class
Program:
Important Questions
1. Write a java program that demonstrates how certain exception types are not allowed to be
thrown.
2. Write the benefits of packages
3. What are the advantages of using an Exception handling mechanism in a program?
4. How can we add a class to a package?
5. Explain about creation and importing packages
6. Explain about access specifiers in packages.
7. Explain about the a)classpath b)Java time package
8. Explain about wrapper classes and its methods and boxing process.
9. Explain about exception handling.
10. Define a Package and Explain about importing a class into Programs?
11. Explain class Math and Wrapper classes in java?
12. Explain about java util classes and interfaces?
13. Explain concept of Temporal adjusters’ class?
14. What is Exception? Write a java program to handle exception handling
15. Write a java program to accept multiple catch blocks in java?
16. Differences between checked exception and unchecked Exception?
UNIT-5
String Handling in Java: Introduction, Interface Char Sequence, Class String, Methods for
Extracting Characters from Strings, Methods for Comparison of Strings, Methods for
Modifying Strings, Methods for Searching Strings, Data Conversion and Miscellaneous
Methods, Class String Buffer, Class String Builder.
Multithreaded Programming: Introduction, Need for Multiple Threads Multithreaded
Programming for Multi-core Processor, Thread Class, Main Thread, Creation of New Threads,
Thread States, Thread Priority, Synchronization, Deadlock and Race Situations, Inter-thread
Communication - Suspending, Resuming, and Stopping of Threads.
Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and
MySQL Connector/J, JDBC Environment Setup, Establishing JDBC Database Connections,
ResultSet Interface, Creating JDBC Application, JDBC Batch Processing, JDBC Transaction
Management

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 of Thread Class

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

1. wait() 2. notify() 3.notifyAll()

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

 The two declarations are equivalent to the following


char s1[]={‘a’,’b’,’c’,’d’};
char s2[]={‘E’,’e’,’1’,’l’};
 Object of class string may also be created by operator new-like object of any other class.
String str=new String(“abcd”);
 In the case of other two classes, the objects can be created only by the operator new as
StringBuffer burstr=new StringBuffer(“abcd”);
StringBuilder buildstr=new StringBuilder(“abcd”);
Storage of Strings
 The memory allocated to a Java program is divided into two segments
(i) Stack
(ii) Heap
 The objects of class String have a special storage facility, which is not available to objects of other two String
classes or to objects of any other class.
 The variables are stored on heap, whereas the program is stored on stack.
 Within the heap, there is a memory segment called ‘String constant pool’.
 The String class objects can be created in two different ways:
String strx = "abcd"; String strz = new String("abcd");
Immutability
String class
 The string objects created by class String are immutable.
 By immutable implies that once an object is created, its value or contents cannot be changed.
 Neither the characters in the String object once created nor their case (upper or lower) can be changed.
 The immutable objects are thread safe and so are the String objects.
StringBuffer class
 The objects created by class StringBuffer are mutable.
 These are stored on the heap segment of memory outside the String constant pool.
 The contents of StringBuffer strings may be changed without creating new objects.
 The methods of StringBuffer are synchronized, and hence, they are thread safe
StringBuilder class
 The objects of class StringBuilder are also mutable but are not thread safe.
 The operations are fast as compared to StringBuffer and there is no memory loss as is the case with String
class.
 The class StringBuilder has the same methods as the class StringBuffer.

Program:
Output:

Concept-9 Interface Char Sequence


 It is an interface in java.lang package.
 It is implemented by several classes including the classes like String, StringBuffer, and StringBuilder.
 It has the following four methods.
Method Description
char charAt(int index) The method returns character value at specified index value.
int length() This method returns the length of this (invoking) character sequence.
CharSequence subsequence
The method returns a subsequence from start index to end index of this sequence
(int startIndex, endIndex)
String toString() The method returns a string containing characters of the sequence in the same
Program:

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:

Concept-11 Methods for Comparison of Strings


Method Description
It is used to know whether or not strings are identical. equals 0:, means the
int compareTo(String str) strings are equal. greater than 0: the caller string is greater than the argument
string. less than 0: the caller string is less than the argument string.
int compareToIgnoreCase It is used to know whether or not string are identical by ignoring the case
(String str) difference
It is used to compare the equality of both the strings. This comparison is case
boolean equals()
sensitive
boolean equalsIgnoreCase() If we want to compare two strings irrespective of their case differences
boolean startsWith(String str) Returns true if a string starts with the given substring
boolean endswith(String str) Returns true if a string ends with the given substring
Program: Output:

Concept-12 Methods for Modifying Strings


Method Description
Using this method, you can extract a part of originally declared string/string
String substring()
object
String substring(int startIndex) Using the startIndex, you specify the index from where your modified string
should start.
String substring(int startIndex, In this method, you give the starting point as well as the ending point of the
int endIndex) new string.
String concat() Using this function you can concatenate two strings.
char replace() This method is used to modify the original string by replacing some
characters from it
String replace(char original,
This method replaces one and only character from the original string.
char replacement)
This method is used to removes the extra white spaces at ending of the string
String trim()
and beginning of the string
Program:

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:

Concept-14 Data Conversion and Miscellaneous Methods


Method Description
boolean contains(CharSequence sequence) It is used to searches the sequence of characters in this string.
It is used to searches a string to find out if it contains the exact
boolean contentEquals(CharSequence chars)
same charsequence of characters in the specified string
It is used to searches a string to find out if it contains the exact
boolean contentEquals(StringBuffer chars)
same Stringbuffer of characters in the specified string
It is used to method converts different types of values into
static String valueOf(int i)
string.
Program:
Output:

Concept-15 Class String Buffer


 Java StringBuffer class is used to create mutable (modifiable) string.
 The StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed. Object Creation using StringBuffer
StringBuffer sb=new StringBuffer();
StringBuffer sb=new StringBuffer("Hello");
StringBuffer sb=new StringBuffer(20);
What is mutable string
 A string that can be modified or changed is known as mutable string.
 StringBuffer and StringBuilder classes are used for creating mutable string.
Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.

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


creates an empty string buffer with the specified capacity as
StringBuffer(int capacity)
length.
Inbuilt Methods in the StringBuffer Class
Method Description
reverse() It is used to reverse the string.
capacity() It is used to return the current capacity.
It is used to return the length of the string i.e. total
length()
number of characters.
substring(int beginIndex, int It is used to return the substring from the specified
endIndex) beginIndex and endIndex.
replace(int startIndex, int endIndex, It is used to replace the string from specified
String str) startIndex and endIndex.
It is used to delete the string from specified
delete(int startIndex, int endIndex)
startIndex and endIndex.
insert(int offset, String s) It is used to insert the specified string with this string
at the specified position.
Programs:
Concept-16 Class String Builder
 Java StringBuilder class is used to create mutable (modifiable) String.
 The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
Constructors of StringBuilder Class
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
It creates an empty String Builder with the specified capacity as
StringBuilder(int length)
length.
Inbuilt Methods in the StringBuilder Class
Method Description
public StringBuilder reverse() It is used to reverse the string.
public int capacity() It is used to return the current capacity.
public char charAt(int index) It is used to return the character at the specified position.
It is used to return the length of the string i.e. total number of
public int length()
characters.
public String substring(int It is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int It is used to return the substring from the specified beginIndex
beginIndex, int endIndex) and endIndex.
public StringBuilder
It is used to append the specified string with this string.
append(String s)
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position.
Programs:
Concept-17 Java Database Connectivity: Introduction
 JDBC stands for Java Database Connectivity, which is a standard Java API for database independent
connectivity between the Java programming language and a wide range of databases.
 It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.
 It is plat independent technology
 The JDBC library includes APIs for each of the tasks commonly associated with database usage:
1. Making a connection to a database
2. Creating SQL or MySQL statements
3. Executing that SQL or MySQL queries in the database
4. Viewing & Modifying the resulting records
Concept-18 JDBC Architecture
The JDBC API supports
1. two-tier processing model
2. three-tier processing model for database access but in general JDBC Architecture consists of two layers·
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
Two Tier Processing Model:
 Here java applications communicates directly with Data base so it requires JDBC Driver to communicate with
Particular database being accessed User sends a QUERY to Data Base then Data Base Sends response to user.
 In this Database is not necessary to present in single machine it can locate on different machines so called
Client-Server Configuration i.e., user machine acts as client and machine having data base acts as server
machine
 Advantages: Easy to maintain & Modification also easy.
 Disadvantages: App performance reduces when no.of clients increases.
Three Tier Processing Model
 Here User sends Queries to middle tier server from middle tier server Queries are send to DB server
 Data Base server takes Queries from middle tier server and process those queries and then sends the response
to middle tier server
 After that Middle tier server sends results back to user
 Advantages: High performance & Security.
 Disadvantages: More complex to maintain.

Concept-19 JDBC Environment Setup


 To start developing with JDBC, you should setup your JDBC environment by following the steps shown
below. We assume that you are working on a Windows platform
 Install Java
 Install JDK from Oracle website
 JAVA_HOME: This environment variable should point to the directory where you installed
 CLASSPATH: This environment variable should have appropriate paths set
 PATH: This environment variable should point to appropriate JRE bin
Install Database (Ex: MySql and MySql Connector J)
 MySQL DB: MySQL is an open source database. You can download it from MySQL Official
Site.(mysql.com)
 We recommend downloading the Default Option because it will download all default softwares. It includes
MySql Connector J Which is useful for JDBC for MySql
 Install the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Accordingly, set
 CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java5.1.8\mysqlconnector-java-
5.1.8-bin.jar.
 Your driver version may vary based on your installation.
Concept-20 Establishing Data Base Connections
 To Connect java Application to data base we need following steps
 Here we are using Mysql data base instead you can use other data base also like Oracle
Step 1: Driver class: Diver class is com.mysql.jdbc.Driver
Step 2: Connection to URL :
Jdbc:mysql://localhost:3306/rcee
Jdbc= is an API
Mysql= data base
Localhost= servername
3306= port number (When installing Mysql we used)
rcee= database name
Step 3: User name : the default user name for mysql data base is root
Step 4: Password : it is the pass word given by the user at the time of installing mysql database
Create a table in database
SQL> create table emp(id int, name varchar(30), age int );
Insert Values into Table
SQL> insert into emp values ( (102,”Tej”,24); (103,”Ram”,26); );
SQL > select * from emp;
Concept-21 ResultSet interface
 Object of ResultSet maintains a cursor priority to row of table
Commonly Used Methods:
boolean next(): it returns true if row is present
boolean previous(): it returns true if previous row is present
boolean first(): first row in result set object
boolean last(): last row in result set object
boolean absolute(int row): it results row if available
Program:
import java.sql.*;
public class MysqlCon {
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/rcee","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Output:
102 Tej 24
103 Ram 23
Concept-22 JDBC Batch Processing
 Instead of executing a single query , we can execute a batch(group) of queries .
 Advantage : it makes performance fast
 The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing
 Methods:
public void addBatch(Query) : it adds query to batch
int[] executeBatch() : it executes batch of queries
Steps:
Load the Driver class
Create connection
Create a statement
Add Query to batch
Execute batch
Close connection
Concept-23 JDBC Transaction Management
 Transaction represents a single unit of work.
 The ACID properties describe the transaction management well.
 ACID stands for Atomicity, Consistency, isolation and durability.
 Atomicity means either all successful or none.
 Consistency ensures bringing the database from one consistent state to another consistent state.
 Isolation ensures that transaction is isolated from other transaction.
 Durability means once a transaction has been committed, it will remain so, even in the event of errors, power
loss etc.
Useful Methods:
void setAutoCommit(boolean status) : It is true by default means each transaction is committed by default
void commit(): commits the transaction
void rollback() : cancels the transaction
Program on Batch processing and Transaction management
import java.sql.*;
public class BpTmEx {
public static void main(String args[]) throws Exception {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cse","root","root");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into student values(45,'rohith',33)");
stmt.addBatch("insert into student values(17,'ABD',40)");
stmt.addBatch("insert into student values(3,'Raina',34)");
stmt.addBatch("insert into student values(36,'Jadeja',32)");
int[] result =stmt.executeBatch();
System.out.println(result.length+" values are inserted ");
con.commit();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Important Question
1. Write a java Program that finds number of vowles, number of characters, and digits in the String
2. Explain about different type of string creation class String class, Stringbuffer class, & StringBuilder class
3. Explain about Methods for Extracting Characters from Strings.
4. Explain about Methods for Comparison of Strings.
5. Explain about Methods for Modifying Strings.
6. Explain about Methods for Searching Strings.
7. Explain about Data Conversion and Miscellaneous Methods
8. Write a java program for comparison of Strings?
9. Write a java program for modification of Strings?
10. What is multi-Threading and need for multi-threading in java? Explain with a java program?
11. Explain states of Threads and Synchronization of Threads?
12. Explain the concept of Inter Thread communication in java?
13. Explain JDBC Architecture and also explain Steps to establish connection to data base using java program?
14. Explain JDBC Batch processing concepts with a java program?
15. Explain concept of JDBC Transaction management?

You might also like