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

OOP JAVA M2 Ktunotes - in

Uploaded by

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

OOP JAVA M2 Ktunotes - in

Uploaded by

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

CST 205 Object Oriented Programming using Java

CST 281 Object Oriented Programming


(As per KTU 2019 Syllabus)

Module 2

Downloaded from Ktunotes.in


Course Outcomes
● CO1 - Write Java programs using the object oriented concepts - classes, objects,
constructors, data hiding, inheritance and polymorphism [Apply]
● CO2 - Utilise data types, operators, control statements, built in packages &
interfaces, Input/Output Streams and Files in Java to develop programs [Apply]
● CO3 - Illustrate how robust programs can be written in Java using exception handling
mechanism [Understand]
● CO4 - Write application programs in Java using multithreading and database
connectivity [Apply]
● CO5 - Write Graphical User Interface based application programs
by utilising event handling features and Swing in Java [Apply]
● CO6 - Practically apply the knowledge of Software Engineering methods such as
Function Oriented Design and Object Oriented Design With a clear emphasis on UML

Downloaded from Ktunotes.in


Modules
Modu Contents Plan Actual
le

1 Approaches to Software Design, OOD, UML, Java introduction 6 10 (+4)

2 Primitive Data types, Operators, Class Fundamentals, Inheritance 9

3 Packages, Interfaces, Exception handling, Input/Output 7

4 Java Library, Collection Framework, Event handling, Multithreading 9

5 Graphical User Interface and Database support 7

Minimum number of lectures : 38~45

Downloaded from Ktunotes.in


Module 2 - Core Java Fundamentals
Primitive Data types - Integers, Floating Point Types, Characters, Boolean. Literals, Type
Conversion and Casting, Variables, Arrays, Strings, Vector class. Operators - Arithmetic
Operators, Bitwise Operators, Relational Operators, Boolean Logical Operators, Assignment
Operator, Conditional (Ternary) Operator, Operator Precedence. Control Statements -
Selection Statements, Iteration Statements and Jump Statements.

Object Oriented Programming in Java - Class Fundamentals, Declaring Objects, Object


Reference, Introduction to Methods, Constructors, this Keyword, Method Overloading, Using
Objects as Parameters, Returning Objects, Recursion, Access Control, Static Members, Final
Variables, Inner Classes, Command Line Arguments, Variable Length Arguments.

Inheritance - Super Class, Sub Class, The Keyword super, protected Members, Calling Order
of Constructors, Method Overriding, the Object class, Abstract Classes and Methods, using
final with Inheritance.

https://www.youtube.com/channel/UCTBjhZB3ni3_NCT9M0XNOpQ

Downloaded from Ktunotes.in


Module 2 Lectures
● 2.1 Primitive Data types - Integers, Floating Point Types, Characters, Boolean
● 2.2 Literals, Type Conversion and Casting, Variables, Arrays, Strings, Vector class.
● 2.3 Operators - Arithmetic Operators, Bitwise Operators, Relational Operators, Boolean
Logical Operators, Assignment Operator, Conditional (Ternary) Operator, Operator
Precedence.
● 2.4 Control Statements - Selection Statements, Iteration Statements and Jump
Statements.
● 2.5 Object Oriented Programming in Java - Class Fundamentals, Declaring Objects
● 2.6 Object Reference, Introduction to Methods
● 2.7 Constructors, this Keyword
● 2.8 Method Overloading, Using Objects as Parameters
● 2.9 Returning Objects, Recursion
● 2.10 Access Control, static Members
● 2.11 Final Variables, Inner Classes
● 2.12 Command-Line Arguments, Variable Length Arguments

Downloaded from Ktunotes.in
Data type
● Data type defines the type of values that a
variable can hold
● Java is statically typed, which means that
all variables must first be declared before
they can be used.
● Java is strongly typed, every
variable/expression has a strictly defined
data type.
● The Java compiler checks all expressions
and parameters to ensure that the types
are compatible.
● Any type mismatches are errors that must
be corrected by the programmer.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Primitive data type
● A primitive type is predefined by the language and type name is a keyword.
● In Java there are 8 primitive data types: byte, short, int , long, char, float,
double, and boolean
● Integers : byte, short, int , and long , which are for whole valued signed
numbers.
● Floating point numbers : float and double , which represent numbers with
fractional precision.
● Characters char , which represents symbols in a character set.
● Boolean boolean , represents true/false values.

Downloaded from Ktunotes.in


Primitive data type - Integer
● The integer data types are used to store whole numbers like 2, 3 -1245 etc.
● There are 4 types to handle signed whole numbers
● In C/C++, size of int is dependant upon the platform.
● In Java, language defines the size.

byte age = 10 ;

Downloaded from Ktunotes.in


Primitive data type - Floating point
● Floating-point numbers: This group includes float and double, which
represent numbers with fractional precision
● Java implements the standard (IEEE–754) set of floating-point types
● float - single-precision 32-bit
● double - precision 64-bit format

Downloaded from Ktunotes.in


Primitive data type - Character
● In Java, the char data type used to store characters is char
● Java uses Unicode to represent characters
● At the time of Java's creation, Unicode required 16 bits.
Thus, in Java char is a 16 bit type.
● Example: char letter = 'A';

Downloaded from Ktunotes.in


Primitive data type - Boolean
● boolean: The boolean data type has only two possible values: true and false.
Use this data type for simple flags that track true/false conditions.
● This data type represents one bit of information, but its "size" isn't something
that's precisely defined
● Size of boolean data type is virtual machine-dependent. Usually 1 byte.
● Values of type boolean are not converted implicitly or explicitly (with casts) to
any other type.
● This is the type returned by all relational operators, as in the case of a < b .
● Example: boolean b;

Downloaded from Ktunotes.in


Java Wrapper Classes
● Primitive type variables and not objects.
● Wrapper classes provide a way to use primitive data types (int, boolean, etc..)
as objects.
● Primitive wrapper classes are used to create an Object that needs to
represent primitive types in java

Downloaded from Ktunotes.in


Literals
● Primitive types are special data types built into the language; they are not
objects created from a class.
● A literal is the source code representation of a fixed value, that do not change
during the execution; literals are represented directly in your code without
requiring computation.
● As shown below, it's possible to assign a literal to a variable of a primitive type
○ boolean result = true;
○ char capitalC = 'C'
○ byte b = 100;
○ short s = 10000;
○ int i = 10 ;

Downloaded from Ktunotes.in


Integer literals
● Integer literal are used to represent a decimal , binary , or hexadecimal value.
● Integer literals are used to initialize variables of integer data types byte, short,
int and long.
● Integer literal that ends with l or L is of type long .
● In Java, a binary literals starts with 0b , and hexadecimal literals starts with
● 0x and rest every integer literal is a decimal literals
● int decInt = 18; // 18 in decimal notation
● int binInt = 0b10010; // 18 in binary notation
● int hexInt = 0x12; // 18 in hexadecimal notation
● long longValue = 123456789L ;

Downloaded from Ktunotes.in


Floating point literals
● A floating point literal is of type float if it ends with the letter F or f
● Otherwise its type is double and it can optionally end with the letter D or
d
● The floating point types (float and double) can also be expressed using
E or e (for scientific notation
● double myDouble = 123.4 ;
● double myDoubleScientific = 1.234e2 ;// same value as d1, but in
scientific notation
● float myFloat = 123.4f ;

Downloaded from Ktunotes.in


Character and String literals
● Literals of types char and String may contain any Unicode (UTF 16)
characters.
● String literals are represented as a sequence of characters surrounded
by double quotes
● character literal is represented as a single character surrounded by
single quotes.
● Java also allows use of escape sequences in string and character
literals. [ \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage
return), \” (double quote), \’ (single quote), and \\(backslash]
● char myChar = 'A '; // Character Literal
● char newLine = n ';';// Character Literal Escape sequence
● String myString = "Java Tutorial "; // String Literal
Downloaded from Ktunotes.in
Underscore characters in numeric literals
● In Java SE 7 and later, any number of underscore characters (_) can appear
anywhere between digits in a numerical literal.
● This feature enables you, for example. to separate groups of digits in numeric
literals, which can improve the readability of your code
● The following example shows other ways you can use the underscore in numeric
literals:
○ long creditCardNumber = 1234_5678_9012_8906L ;
○ long socialSecurityNumber = 999_99_990 ;
○ float pi = 3.14_15F;
○ long hexBytes = 0xFF_EC_DE_AB ;
○ long hexWords = 0xCAFE_AABB ;
○ long maxLong = 0x7fff_ffff_ffff_ffffL ;
○ byte nybbles = 0b0010_0101 ;
○ long bytes = 0b11010010_01101001_10010100_10010010;
Downloaded from Ktunotes.in
Underscore characters in numeric literals
● You can place underscores only between digits; you cannot place underscores
in the following places
● At the beginning or end of a number
● Adjacent to a decimal point in a floating point literal
● Prior to an F or L suffix
● In positions where a string of digits is expected
// Invalid: cannot put underscores adjacent to a decimal point
float pi1 = 3_.1415F;
// Invalid: cannot put underscores prior to an L suffix
long socialSecurityNumber1 = 999_99_9999_L;
// Invalid: cannot put underscores in the 0x radix prefix
int x4 = 0_x52;
// Invalid: cannot put underscores at the beginning of a number
int x5 = 0x_52;
// OK (hexadecimal literal)
int x6 = 0x5_2;
// OK (decimal literal)
int x3 = 5_______2;
Downloaded from Ktunotes.in
Variables
● The variable is the basic unit of storage in a Java program.
● A variable is defined by the combination of an identifier , a
type , and an optional initializer .
● In addition, all variables have a scope , which defines their
visibility, and a lifetime which indicates how long the variable
stays alive in the memory
● Here are several examples of variable declarations of
various types. Note that some include an initialization
○ int a, b, c; // declares three ints , a, b, and c
○ int d = 3, e, f = 5; // declares three more ints , initializing d and f.
○ byte z = 22; // initializes
○ String Name = “Samia” ;

Downloaded from Ktunotes.in


Variable naming rule
● Variable names are case sensitive.
● A variable's name can be any legal identifier
● The only allowed characters for identifiers are all alphanumeric characters
(characters([A Z a z 0 9 ]), ‘$‘(dollar sign) and ‘_‘
● For example “geek@” is not a valid java identifier as it contain ‘@’ special
character, geek$ is valid.
● Identifiers should not start with digits([0 9])9]).
● Reserved Words can’t be used as an identifier.
● For example “ int while = 20;” is an invalid statement as while is a reserved
word.

Downloaded from Ktunotes.in


Variable naming convention
● If the name you choose, consists of only one word, spell that word in all
lowercase letters.
● If it consists of more than one word, capitalize the first letter of each subsequent
word. This style is known as camel case.
● Examples
● gearRatio , currentGear
● If your variable stores a constant value, such as static final int
● NUM_GEARS = 6 , the convention changes slightly, capitalizing every letter
and separating subsequent words with the underscore character.

Downloaded from Ktunotes.in


Variable scope
& life time

Downloaded from Ktunotes.in


Types of Variables

Downloaded from Ktunotes.in


Type conversion and casting
● When a data type is converted into another type is called type conversion
● When a variable is converted into a different type, the compiler basically
treats the variable as of the new data type.
● Type of Type Conversion In Java
● Implicit Conversion
● Explicit Conversion

Downloaded from Ktunotes.in


Implicit conversion.
● Implicit or automatic conversion compiler will automatically change one type of
data into another without data loss.
● Implicit or automatic conversion can happen if both type are compatible and
target type is larger than source type.
● If you assign an integer value to a floating point variable, the compiler will insert
code to convert the int to a float.
● In implicit conversion a smaller type is converted into a larger thus it is also
known as widening conversion.

Downloaded from Ktunotes.in


Explicit conversion.
● There may be situations when we want to convert a value having larger type to
a smaller type.
● In this case casting needs to be performed explicitly.
● Explicit casting allows you to make this type conversion explicit, or to force it
when it wouldn’t normally happen.
● Syntax: (type) expression
● To perform type casting, put the desired type including modifiers inside
parentheses to the left of the variable or constant you want to cast.

Downloaded from Ktunotes.in


Upcasting & Downcasting.
● Just like the data types, the objects can also be type casted.
● In objects, there are only two types of objects (i.e.) parent object and child object.
● One type of object (i.e.) child or parent can be converted to another.
● There are two types of typecasting. They are:
● Upcasting: Upcasting is the typecasting of a child object to a parent object.
Upcasting can be done implicitly.
● Downcasting: Similarly, downcasting means the typecasting of a parent object to
a child object. Downcasting cannot be implicitly.

Downloaded from Ktunotes.in


Arrays in Java
● Arrays are used to store multiple values of
same type, in a single variable
● Arrays are objects which store multiple
values of the same type
● It can hold primitive types as well as object
references.
● Features of Array
● Arrays are objects
● They can even hold the reference
variables of other objects
● They are created during runtime (new)
● They are dynamic, created on the heap
● The Array length is fixed.

Downloaded from Ktunotes.in


Array declaration
● To declare an array, define the variable type with square brackets
● Eg: int[] anArray;
● You can also place the brackets after the array's name:
● // this form is discouraged
● float anArrayOfFloats[];
● However, convention discourages this form; the brackets identify the array type
and should appear with the type designation.

Downloaded from Ktunotes.in


Array declaration
● To declare an array, define the variable type with square brackets
● Eg: int[] anArray; // Creates array reference
● You can also place the brackets after the array's name:
● // this form is discouraged
● float anArrayOfFloats[]; // Creates array reference
● However, convention discourages this form; the brackets identify the array type
and should appear with the type designation.

Downloaded from Ktunotes.in


Definition, Initializing and Accessing arrays
One way to create an array is with the new operator.
// declares an array of integers
int [] anArray // create an array of integers
anArray = new int [10] ;

To assign values to each element of the array


anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

Each array element is accessed by its numerical index


System.out.println("Element 1 at index 0: " + anArray [0]);
System.out.println("Element 2 at index 1: " + anArray [1]);
System.out.println("Element 3 at index 2: " + anArray [2]);
Downloaded from Ktunotes.in
Array length
Alternatively, you can use the shortcut syntax to create and initialize an array
int[] anArray = {100, 200, 300};
Here the length of the array is determined by the number of values provided between
braces and separated by commas.

To find out how many elements an array has, use the length property:
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars.length );// Outputs 3

Downloaded from Ktunotes.in


Multidimensional Arrays
● A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example int[][] anArray = new int
[3][4];
● To create a two dimensional array, add each array within its own set of curly
braces:
● int [][] anArray ={ {1, 2, 3}, {4, 5, 6, 9} };
● //calculate the length of each row
● System.out.println("Length of row 1: " + anArray [0 ].length);
● System.out.println("Length of row 2: " + anArray [1 ].length);

Downloaded from Ktunotes.in


Iterating array elements
● We can use for...each loop or for loop to access elements of the multidimensional
array.

Downloaded from Ktunotes.in


Copying array
● The System class has an arraycopy method that you can use to efficiently copy
data from one array into another
public static void arraycopy (Object src , int srcPos, Object dest , int destPos ,
int length) ;

Downloaded from Ktunotes.in


Sorting array

Downloaded from Ktunotes.in


Searching array

Downloaded from Ktunotes.in


Strings
● In Java, string is basically an object of String
class, that represents sequence of char
values. An array of characters works same as
Java string
● Strings are treated as objects of class String
which represents character strings.
● All string literals in Java programs, such as
"abc", are implemented as instances of this
class.

char[] ch={'h','e','l','l','o'};
String s=new String(ch);
This is same as that of
String s="hello";
Downloaded from Ktunotes.in
String literals vs objects
● String objects are created using new keyword
● String s1 = new String("Java");
● String s2 = new String("Java");
● System.out.println(s1 == s2); //false
● String literals are created by placing the string in
double quotes.
● String s3 = "Java";
● String s4 = "Java";
● System.out.println(s3 == s4);//true
● Here == (equality) is not checking the content of the
stings.
● String literals are stored in a special area called String
Constant Pool in program heap.
Downloaded from Ktunotes.in
Immutability of string
● Strings are constant; their values cannot be changed(immutable) after they
are created. StringBuffer support mutable strings.
● String objects are immutable, so they can be shared.
● In Java, String is a final and immutable class.
● It cannot be inherited, and once created, we can not alter the object.

Downloaded from Ktunotes.in


String length and String concatenation
● The length of a string is the number of characters that it contains.
● To obtain this value, call the length( ) method.

+ operator concatenates two strings, producing a new


String object as the

result

Downloaded from Ktunotes.in


String comparison
● equals( ) and equalsIgnoreCase()
● These functions produces boolean output.
● It has this general form: boolean equals(Object str)

String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); // true

String s1 = "Hello";
String s2 = "HELLO" ;
s1.equals(s2); // false
s1.equalsIgnoreCase(s2); // true

Downloaded from Ktunotes.in


String comparison
startsWith( ) and endsWith ()

● The startsWith( ) method determines whether a given String begins with a


specified string.
● endsWith( ) determines whether the String in question ends with a specified
string.
● They have the following general forms
○ boolean startsWith (String str)
○ boolean endsWith (String str)

Downloaded from Ktunotes.in


String comparison: compareTo() method
● To find less than, equal to, or greater than relations between strings
● A string is less than another if it comes before the other in dictionary order
● A string is greater than another if it comes after the other in dictionary order

Downloaded from Ktunotes.in


String comparison: equals() vs ==
● equals( ) method compares the characters inside a String object.
● == operator compares two object references to see whether they refer to the
same instance

Downloaded from Ktunotes.in


String searching
● The String class provides two methods that allow you to search a string for a
specified character or substring
● indexOf( ) Searches for the first occurrence of a character or
● lastIndexOf( ) Searches for the last occurrence of a character or

Downloaded from Ktunotes.in


substring() method
● Used to get the substring of a given string based on the passed indexes
○ String substring( int beginIndex )
○ Returns the substring starting from the specified index i.e beginIndex and extends to the
character present at the end of the string
● String substring( int beginIndex , int endIndex
○ The substring begins at the specified beginIndex and extends to the character at index
endIndex - 1.
○ Thus the length of the substring is endIndex - beginIndex .

Downloaded from Ktunotes.in


String methods

Downloaded from Ktunotes.in


Vector Class in Java
● Vector implements a dynamic array, ie growable array of objects.
● Like an array, it contains elements that can be accessed using an integer index
.
● It is found in the java.util package and implements the List interface , so we can
use all the methods of List interface.
● It is synchronized and due to which it gives poor performance in searching,
adding, delete and update of its elements.
● Contains many legacy methods that are not part of the collections framework.
● Vector proves to be very useful if you don't know the size of the array in
advance or you just need one that can change sizes over the lifetime of a
program.

Downloaded from Ktunotes.in


Creating a Vector Here is how we can create vectors in Java

● Import Vector class. (import java.util.Vector ;)

Vector<Type> vector = new Vector<>();

For example

// create Integer type linked list

Vector<Integer> vector= new Vector<>();

// create String type linked list

Vector<String> vector= new Vector<>();

Downloaded from Ktunotes.in


Add elements to vector

Downloaded from Ktunotes.in


Access vector elements

Downloaded from Ktunotes.in


Remove vector elements

Downloaded from Ktunotes.in


Important Vector methods

Downloaded from Ktunotes.in


Operators in Java
● Operators are special symbols that perform specific
operations on one, two, or three operands, and then return
a result.
● An operator is a token that tells the computer to perform
certain mathematical or logical operations on variables and
literals.

Downloaded from Ktunotes.in


Arithmetic operators

Downloaded from Ktunotes.in


Arithmetic operators - Compound operators
● a+=10 is same as that of a = a + 10
● += is an example for Compound Assignment Operators, also known as
Shorthand Assignment Operators.
● It's called shorthand because it provides a short way to assign an expression
to a variable.
● This operator can be used to connect Arithmetic operator with an Assignment
operator

Modulus operator (%)

A = 5, B =2

C = A%B

C=?
Downloaded from Ktunotes.in
++ / -- ● A++ is same as A = A + 1
● A-- is same as A = A - 1
● ++A is pre increment, change
first then use the value when
there is an assignment.
● A++ post increment
● Use the value then change
(when there is an assignment)

Downloaded from Ktunotes.in


Assignment operator
● Assignment operators are used to assign
values to variables.
● Eg: int A = C + 10 ;
● When the target variable and one of the
operand are same then we can use
shorthand / compound operators. ( Not
applicable for ternary operators )

Downloaded from Ktunotes.in


Unary Operators
● Java unary operators are the types that need only one operand to perform any operation.
● It consists of various arithmetic, logical and other operators that operate on a single
operand

Downloaded from Ktunotes.in


Java Comparison/Relational Operators
● Comparison operators are used to compare two values
● Produces Boolean result

Downloaded from Ktunotes.in


Java Boolean Logical Operators
● Logical operators are used to determine the logic between variables or values.
● Produces boolean result.
● In Java (&&) AND and (||) OR supports short circuiting

Downloaded from Ktunotes.in


Java Bitwise Operators
● Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Downloaded from Ktunotes.in


Java Shift Operators (Unsigned right shift)
● >>> Right shift with zero fill or unsigned right shift is a newly introduced operator in Java

Downloaded from Ktunotes.in


Java Ternary Operator
● As the name ternary suggests, it is the only operator in Java consisting of three operands.
● The ternary operator can be thought of as a simplified version of the if-else statement with a
value to be returned.
● Syntax
variable = (condition) ? block1 : block2 ;

Downloaded from Ktunotes.in


Type Comparison Operator
● In Java, the instanceof keyword is a binary operator. Result will be boolean
● It is used to check whether an object is an instance of a particular class or not.
● The operator also checks whether an object is an instance of a class that implements an
interface. Syntax: object instanceof ClassName/InterfaceName;

Downloaded from Ktunotes.in


Expression, Statement, Block
Expressions
● An expression is a construct made up of variables, operators, and method invocations.
● Constructed according to the syntax of the language, that evaluates to a single value.
○ int result = 1 + 2 // result is now 3
● Compound expressions are created from various smaller expressions.
○ Eg: a = x + y / 100 // ambiguous
Statements
● Statements are roughly equivalent to sentences in natural languages.
● A statement forms a complete unit of execution. ; indicates the boundary.
● Expression statement
○ Bicycle myBike = new Bicycle();
● Declaration statements - A declaration statement declares a variable.
○ double aValue = 8933.234;
● Control flow statements regulate the order in which statements get executed.
Block
A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed.
Downloaded from Ktunotes.in
Expression evaluation in Java

Evaluate following expressions.


● A = 10 + 5 ;
● C = 10 * 2 - 3 ;
Evaluate 2*x-3*y ?
● (2x)-(3y) or 2(x-3y) which one is correct?
Evaluate A / B * C
● A / (B * C) or (A / B) * C Which one is correct?
To answer these questions satisfactorily one has to understand the
priority or the order in which these operators are evaluated.

Downloaded from Ktunotes.in


Operator Precedence
● Operator precedence determines the order in which the operators in an expression are
evaluated.
● Precedence order. When two operators share an operand the operator with the higher
precedence goes first.
○ For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) +
3 since multiplication has a higher precedence than addition.
● Associativity. When an expression has two operators with the same precedence, the
expression is evaluated according to its associativity.
○ For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables
with the value 17, since the = operator has right-to-left associativity (and an
assignment statement evaluates to the value on the right hand side).
○ On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has
left-to-right associativity.
○ Some operators are not associative: for example, the expressions
(x <= y <= z) and x++-- are invalid.

Downloaded from Ktunotes.in


Operator Precedence
Order of evaluation of subexpressions.
● Associativity and precedence determine in which order Java applies operators to
expressions but they do not determine in which order the subexpressions are
evaluated.
● In Java, subexpressions are evaluated from left to right (when there is a choice).
● So, for example in the expression A() + B() * C(D(), E()), the subexpressions are
evaluated in the order A(), B(), D(), E(), and C().
● It is considered poor style to write code that relies upon this behavior (and different
programming languages may use different rules).
Short circuiting.
● When using the conditional and and or operators (&& and ||), Java does not evaluate
the second operand unless it is necessary to resolve the result.
● This allows statements like if (s != null && s.length() < 10) to work reliably.
● Programmers rarely use the non short-circuiting versions (& and |) with boolean
expressions.

Downloaded from Ktunotes.in


Precedence table Highest level to lowest

Downloaded from Ktunotes.in


Operator Precedence

Downloaded from Ktunotes.in


Control Statements
● Default execution order of statements in a program is sequential, ie one after the other
from top to bottom.
● Using control statement, this execution sequence of the program can be altered.
● A control statement in java is a statement that determines whether the other
statements will be executed or not.

Downloaded from Ktunotes.in


Selection Statements
● In java, the selection statements are also known as decision making statements or
branching statements or conditional control statements.
● The selection statements are used to select a part of the program to be executed
based on a condition.
● Java provides the following selection statements.

1. if statement
2. if-else statement
3. nested if statement
4. if-else if statement (if else if ladder)
5. switch statement

Downloaded from Ktunotes.in


Selection if statement
● In java, we use the if statement to test a condition and decide the execution of a block
of statements based on that condition result.

Downloaded from Ktunotes.in


Selection: if-else statement
● if-else statement to test a condition and pick the execution of a block of statements out
of two blocks based on that condition result

Downloaded from Ktunotes.in


Selection: nested if statement
● Writing an if statement inside another if-statement is called nested if statement.

Downloaded from Ktunotes.in


Selection: if else if (if else if ladder)
● The if-else-if ladder statement executes one condition from multiple statement block.

Downloaded from Ktunotes.in


Selection: switch statement
● Switch statement is used for executing one statement from multiple conditions.
● It is similar to an if-else-if ladder.
● In a switch statement,the expression can be of byte, short, char and int data types.
● From JDK7 enum, String class and the Wrapper classes can also be used.
● Following are some of the rules while using the switch statement:
○ There can be one or N numbers of cases.
○ The values in the case must be unique.
○ Each statement of the case can have a break statement. It is optional.

Downloaded from Ktunotes.in


Selection: switch statement

Downloaded from Ktunotes.in


Selection: switch statement

Downloaded from Ktunotes.in


Iteration Statements (Loops)
● A loop statement allows us to execute a
statement or group of statements multiple
times

Downloaded from Ktunotes.in


Iteration:for loop

Downloaded from Ktunotes.in


Enhanced for loop (for each)
● As of Java 5, the enhanced for loop was introduced.
● This is mainly used to traverse collection of elements including arrays
● Syntax of enhanced for loop.
○ for(declaration : expression)
○ {
○ // Statements
○ }
● Declaration − The newly declared block variable, is of a type compatible with
the elements of the array you are accessing.
● This variable will be available only within the for block and its value would be
the same as the current array element.
● Expression − This evaluates to the array you need to loop through.
● The expression can be an array variable or method call that returns an array.

Downloaded from Ktunotes.in


Enhanced for loop (for-each)

Downloaded from Ktunotes.in


Notes on for-each
● For-each loops are not appropriate when you
want to modify the array.
● For-each loops do not keep track of index. So we
can not obtain array index using For-Each loop.
● For-each only iterates forward over the array in
single steps (ie, i+2 is not possible)
● For-each cannot process two decision making
statements at once
// cannot be easily converted to a for-each loop
for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i]) { ...
}
}
Downloaded from Ktunotes.in
while loop
● Entry controlled loop to repeat the loop body.
● When the number of iteration is not fixed then while loop is used

Downloaded from Ktunotes.in


do while loop
● Exit controlled loop to repeat the loop body.
● Irrespective of the loop condition, loop body will be executed at least once.

Downloaded from Ktunotes.in


Nested loops
● A nested loop is a (inner) loop that appears in the
loop body of another (outer) loop.
● The inner or outer loop can be any type: while, do
while, or for.
● For example, the inner loop can be a while loop
while an outer loop can be a for loop. Of course,
they can be the same kind of loops too.

Downloaded from Ktunotes.in


Labeled statements
● A label is a name attached to a statement. [ labele_name : statement… ]
● A goto statement in C/C++ programming provides an unconditional jump from the
'goto' to a labeled statement in the same function
● Java does not have goto statement, but java supports label.
● The only place where a label is useful in Java is right before nested loop.
● You can attach a label name just before the beginning of a loop.
● Label name can be used with break/continue statement for unconditional jump.

Downloaded from Ktunotes.in


Jump statements
● Loop control statements change execution from its normal sequence.
● When execution leaves a scope, all automatic objects that were created in that
scope are destroyed.

break statement

● Terminates the loop or switch statement and transfers execution to the


statement immediately following the loop or switch.
● Has two forms: labeled and unlabeled.

continue statement

● Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
● Has two forms: labeled and unlabeled.

return statement
Downloaded from Ktunotes.in
break;

Downloaded from Ktunotes.in


Labeled break;
● According to nested loop, if we put break statement in inner loop, compiler will jump out
from inner loop and continue the outer loop again.
● To jump out from the outer loop, we can use labeled break.

Downloaded from Ktunotes.in


continue;

Downloaded from Ktunotes.in


Labeled continue;
● In the case of nested loops, the continue skips the current iteration of the innermost loop.
● To skip the current iteration of the outer loop, labeled continue can be used.

Downloaded from Ktunotes.in


return statement
● The return statement exits from the
current method, and control flow returns to
where the method was invoked.
● The return statement has two forms: one
that returns a value, and one that doesn't.
● To return a value, simply put the value (or
an expression that calculates the value)
after the return keyword.
● return ++count;
● The data type of the returned value must
match the type of the method's declared
return value.
● When a method is declared void, use the
form of return that doesn't return a value.
● return;

Downloaded from Ktunotes.in


OO Concepts: Class & Object
CLASS

● A class is a blueprint or prototype from


which objects are created
● A class is a generalized description of
an object. No physical existence.
● Acts as a type or category.

OBJECT

● An object is an instance of a class


● Objects are real-world entities that has
their own state and behavior.
● An object has physical existence
Downloaded from Ktunotes.in
OOP in Java - Class Fundamentals
● Everything in Java is associated with classes and
objects, along with its attributes and methods
● Class members can be either the part of
instance(object) or Class (static members)

Downloaded from Ktunotes.in


Class members
● A class can contain methods and member variables.
● Class members can be either the part of instance(object)
or Class (static members).
● Unless otherwise specified, a member declared within a
class is an instance member.

Downloaded from Ktunotes.in


public class Puppy {
Creating Objects String m_name; // Member variable
● In Java, the new keyword is used to create public Puppy() { }
new objects (instance of class). public Puppy(String name) {
● There are three steps when creating an m_name = name ; }
object from a class −
1. Declaration − A variable declaration with a Public void whoareyou()
variable name with an object type. { System.out.println(“I am “+m_name);}
2. Instantiation − The 'new' keyword is used to
create the object. public static void main(String args[]){
3. Initialization − The 'new' keyword is Puppy myPuppy = new
followed by a call to a constructor. This call Puppy(“Tommy”);
initializes the new object myPuppy.whoareyou();}
}
Puppy myPuppy ; // Declaration
myPuppy = new Puppy(); // Instantiation
myPuppy = new Puppy(“Tommy”); //Initialization

Downloaded from Ktunotes.in


Creating Objects Puppy myPuppy ; // Declaration

● In Java, the new keyword is used to create NULL


new objects (instance of class). myPuppy
● There are three steps when creating an
object from a class − myPuppy = new Puppy(); // Instantiation
1. Declaration − A variable declaration with a Object Puppy object, name
variable name with an object type. address not assigned
2. Instantiation − The 'new' keyword is used myPuppy
to create the object.
3. Initialization − The 'new' keyword is
followed by a call to a constructor. This call myPuppy = new Puppy(“Tommy”);
//Initialization
Object
initializes the new object. Puppy object, name :
address Tommy
myPuppy

Downloaded from Ktunotes.in


Assigning Object Reference Variables
● When you assign one object reference variable to another object reference variable, you are
not creating a copy of the object, you are only making a copy of the reference.

Box b1 = new Box();


Box b2 = b1;

● When you assign null or another value to an object reference, you are not making any
change to the object. Change is only to the reference (link).
b1 = null; // removes the link between the object and b1.

Downloaded from Ktunotes.in


Accessing Instance Variables and Methods
● A class's methods can access the class's instance variables and call its methods. In
particular, the main method for a class is often used to test the class's methods.

● An instance variable is accessed with the expression


referenceVariable.instanceVariableName. Similarly, a method is called with the
expression referenceVariable.methodName (parameters).

● Instance variables and methods are accessed via created objects


● /* First create an object */
● ObjectReference = new Constructor();
● /* Now call a variable as follows */
● ObjectReference.variableName;
● /* Now you can call a member method as follows */
● ObjectReference.MethodName();
● Default values for static and non-static variables are same.
● primitive integers(long, short etc): 0
● primitive floating points(float, double): 0.0
● boolean: false , object references:
Downloaded null from Ktunotes.in
Sample
program

Downloaded from Ktunotes.in


Static variables
● A static variable is common to
all the instances (or objects)
of the class because it is a
class level variable.
● Static variables can be
accessed by calling with the
class name ClassName.
VariableName.
● Static variables are initialized
when class is loaded.
● Static variables are initialized
before any object of that class
is created.
● Static variables are initialized
before any static method of
the class executes.

Downloaded from Ktunotes.in


methods
● Methods are same as that of the functions
in C. But in Java they will be part of any
class declaration.
● A method is a block of code which only
runs when it is called.
● You can pass data, known as parameters,
into a method.
● Methods are used to perform certain
actions, and they are also known as
functions.

Downloaded from Ktunotes.in


Instance methods (non static methods)
● Instance method are methods which require an object of its class to be created before
it can be called.
● To invoke a instance method, we have to create an Object of the class in within which
it defined.
● Memory allocation: These methods themselves are stored in heap but the parameters
and their local variables and the value to be returned are allocated in stack.
● They can be invoked simply using the method name, by the instance methods within
the same/derived class in which they reside.
● From unrelated classes or from static methods, instance methods can be called only
by creating the class object. ie objectname.methodname();
● Instance method(s) belong to the Object of the class not to the class i.e. they can be
called after creating the Object of the class.
● Every individual Object created from the class has its own copy of the instance
method(s) of that class.
● They can be overridden since they are resolved using dynamic binding at run time.

Downloaded from Ktunotes.in


Instance methods
(non static
methods)

Downloaded from Ktunotes.in


static methods
● These methods are declared with static modifier.
● Static methods are the methods in Java that can be called without creating an object
of class.
● They are referenced by the class name itself or reference to the Object of that class.
● Static method(s) are associated to the class in which they reside i.e. they can be
called even without creating an instance of the class i.e
ClassName.methodName(args).
● They are designed with aim to be shared among all Objects created from the same
class.
● Static methods can not be overridden. But can be overloaded since they are resolved
using static binding by compiler at compile time.
● They can directly access only the static methods and static variables of their class

Downloaded from Ktunotes.in


1. [line 6] result is a nonstatic (instance) variable.
Cannot be directly accessed from static method
add();
2. [line 7] printResult() is another non-static
member. Cannot be accessed directly from static
method add()
3. [line 29] static method main cannot directly
access a non-static method nonStaticMethod()

Downloaded from Ktunotes.in


public class Puppy {
Constructor String m_name; // Member variable
● A constructor is to initialize an public Puppy() { }
object(give values to instance variables) public Puppy(String name) {
m_name = name ; }
immediately upon creation.
● Constructor is a special method inside Public void whoareyou()
the class. { System.out.println(“I am “+m_name);}
● Constructor has the same name as the
class in which it resides. No return type. public static void main(String args[]){
● Once defined, the constructor is Puppy myPuppy = new
automatically called immediately after Puppy(“Tommy”);
the object is created, before the new myPuppy.whoareyou();}
operator completes. }

myPuppy = new Puppy(“Tommy”);


//Initialization
Object Puppy object, name :
address Tommy
myPuppy
Downloaded from Ktunotes.in
public class Puppy {
Constructor String m_name; // Member variable
● Constructors have no return type, not public Puppy() { } // Default constructor
even void. public Puppy(String name) {
m_name = name ; }
● This is because the implicit return type
of a class’ constructor is the class type Public void whoareyou()
itself. { System.out.println(“I am “+m_name);}
● Two types of constructors
1. Default constructor – has no public static void main(String args[]){
arguments Puppy myPuppy = new
2. Parameterized constructor –has Puppy(“Tommy”);
arguments(parameters) myPuppy.whoareyou();}
}

myPuppy = new Puppy(“Tommy”);


//Initialization
Object Puppy object, name :
address Tommy
myPuppy
Downloaded from Ktunotes.in
Default constructor
● The following statement
creates an object of class Box.
● Box mybox1 = new Box();
● Here new Box( ) is calling the
Box( ) constructor.
● When we do not explicitly
define a constructor for a class,
then Java creates a default
constructor for the class.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
public class Puppy {
Parameterized Constructors String m_name; // Member variable
public Puppy() { }
● Constructors with arguments are public Puppy(String name) {
called parameterized constructors. m_name = name ; }
● Arguments can be of primitive data
Public void whoareyou()
types or objects.
{ System.out.println(“I am “+m_name);}

public static void main(String args[]){


Puppy myPuppy = new
Puppy(“Tommy”);
myPuppy.whoareyou();}
}

myPuppy = new Puppy(“Tommy”);


//Initialization
Object Puppy object, name :
address Tommy
myPuppy
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Parameterized constructor(contd.)
Box mybox1 = new Box(10, 20, 15);
•Here the values 10, 20, and 15 are passed to the Box( ) constructor when new
creates the object mybox1.
•The parameterized constructor is
Box(double w, double h, double l)
{
width = w;
height = h;
length = l;
}

•Thus, value of mybox1 object’s width, height, and depth will be set as 10, 20,
and 15 respectively.
Downloaded from Ktunotes.in
Check the output of this program??
● Instance variables are hidden
(not accessible) due to the
function parameters with same
name.

Downloaded from Ktunotes.in


Instance variable hiding
● We can have local variables, including formal parameters to methods, with
same same name of the class’ instance variables(attributes).
● But when a local variable has the same name as that of an instance
variable, the local variable hides the instance variable.
● this keyword helps to solve this situation.
● Use this. along with instance variables allow as to explicitly access the
instance variable.

Downloaded from Ktunotes.in


The this Keyword
● The this keyword can be used inside any method to refer to the current
object.
● this is always a reference to the object on which the method was invoked.
● this can be used to refer current class instance variable.
● this can be used to invoke current class method (implicitly)
● this() can be used to invoke current class constructor.
● this can be passed as an argument in the method call.
● this can be passed as argument in the constructor call.

Downloaded from Ktunotes.in


this -Example
Box(int w, int h, int l)
{
this.width = w;
this.height = h;
this.length = l;
}
Here this will always refer to the object invoking the
method
Downloaded from Ktunotes.in
Check the output of this program??
● Instance variables are hidden (not
accessible) due to the function
parameters with same name. But
they are accessed using this
keyword

Downloaded from Ktunotes.in


Instance variable hiding-using this (contd.)
•// Use this to resolve namespace collisions.
class Box
{

double width
double length;
double height
Box(double width, double height, double length)
{
this.width = width;
this.length = length;
this. height = length;
}} Downloaded from Ktunotes.in
Method Overloading
● It is possible to define two or more methods with same name within the same
class, but their parameter declarations should be different.
● This is called method overloading.
● This is a form of polymorphism (many forms)
● Overloaded methods must differ in the type and/or number of their
parameters. (return types is not significant.)
● When an overloaded method is invoked, Java uses the type and/or number of
arguments to determine which version of the overloaded method to actually
call.

Downloaded from Ktunotes.in


•In the example ,test( ) is overloaded three
times.

–The first version test() takes no parameters,

–the second test(int a)takes one integer


parameter

–the thrd test(int a,int b) takes two integer


parameters.

Downloaded from Ktunotes.in


Method Overloading
•When an overloaded method is called, Java looks for a
match between the arguments used to call the method
and the method’s parameters

•This match need not always be exact.


–In some cases, Java’s automatic type conversions can play
a role in overload resolution.


Downloaded from Ktunotes.in
Overloading -through automatic type conversions

Downloaded from Ktunotes.in


Overloading -through automatic type conversions(contd.)

•In this example when test( ) is called with an integer


argument inside .
–Overload, no matching method is found with int as
argument.
•However, Java can automatically convert an integer
into a double, and this conversion can be used to
resolve the call.
–Therefore, when test(int) is not found, Java elevates int to
double and then calls test(double).
Downloaded from Ktunotes.in
Overloading Constructors
•Constructors can be overloaded. public class Puppy {
String m_name; // Member variable
Because a class can have any public Puppy() { }
number of constructors public Puppy(String name) {
m_name = name ; }
–one default constructor, many
Public void whoareyou()
parameterized constructors { System.out.println(“I am “+m_name);}
class A
public static void main(String args[]){
{ Puppy myPuppy = new
A() { //statements} Puppy(“Tommy”);
myPuppy.whoareyou();}
A(int a) { //statements} }
A(int a,float b) { //statements}
} Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Using Objects as Parameters

•We can pass objects as arguments(parameters) to


function(method).

•Objects are passed by reference(call by reference).

● Primitive types are passed by value


● Objects are passed by reference

Downloaded from Ktunotes.in


Object as parameters

Downloaded from Ktunotes.in


Object as parameters

Downloaded from Ktunotes.in


Object to initialize another object (Copy constructor)

Downloaded from Ktunotes.in


Passing arguments to function
● Java always passes parameter variables by value.
● Object variables in Java always point to the real object in the memory heap.
● A mutable object's value can be changed when it is passed to a method.
● An immutable object's value cannot be changed, even if it is passed a new value.
● “Passing by value” refers to passing a copy of the value.
● “Passing by reference” refers to passing the real reference of the variable in
memory.

Effect:

•// Primitive types(int,char,double etc.) are passed by value.


•// Mutable Objects are passed by reference.
•// Immutable Objects are passed by value. Eg String
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
● A method can return any type of data,
Returning objects ● Primitive data (int ,float, char, double etc.)
● class types(objects) that you create.

Downloaded from Ktunotes.in


Recursion
● Recursion is the process of defining
something in terms of itself.
● A method that calls itself is called
recursive function.
● Complex logics can be implemented
recursively.
● Due to the repeated function calls,
performance is less.
● Stack overflow is possible when the
repeated function calls exceed stack
size.
● Consider the example of below method
invocation factorial(4);
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Recursion - Tower of Hanoi
● The objective of the puzzle is to
move the entire stack to another rod,
obeying the following simple rules:
● 1) Only one disk can be moved at a
time.
● 2) Each move consists of taking the
upper disk from one of the stacks
and placing it on top of another
stack i.e. a disk can only be moved if
it is the uppermost disk on a stack.
● 3) No disk may be placed on top of a
smaller disk.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Access Control
● Through encapsulation, we can
control what parts of a program can
access the members of a class.
● By controlling access, you can
prevent misuse.
● How a member can be accessed is
determined by the access specifier
that modifies its declaration
● Java’s access specifiers are
● public
● private
● protected
● default
Downloaded from Ktunotes.in
[UML]Member visibility

PRIVATE
PROTECTED DEFAULT /
PACKAGE

PUBLIC

Downloaded from Ktunotes.in


Private
● The private access modifier is specified using the keyword private.
● The methods or data members declared as private are accessible only within
the class in which they are declared.
● Any other class of same package will not be able to access these members.
● Top level Classes or interface can not be declared as private because
● private means “only visible within the enclosing class”.
● Objectname.variable name is not allowed for private members

PRIVATE

Downloaded from Ktunotes.in


PRIVATE

Downloaded from Ktunotes.in


Default
● Default: no modifier used [UML terminology: package ]
● When no access modifier is specified for a class , method or data member – It
is said to be having the default access modifier by default.
● The data members, class or methods which are not declared using any
access modifiers i.e. having default access modifier are accessible only
within the same package.

DEFAULT /
PACKAGE

Downloaded from Ktunotes.in


DEFAULT /
PACKAGE

Downloaded from Ktunotes.in


Protected
● The protected access modifier is specified using the keyword protected.
● The methods or data members declared as protected are accessible within
same package or sub classes in different package.
● Top level Classes or interface can not be declared as protected because
● protected means “only visible within the enclosing class and any subclasses”
● Hence private/protected modifiers in terms of application to classes, they
apply only to nested classes and not on top level classes

PROTECTED

Downloaded from Ktunotes.in


PROTECTED

Downloaded from Ktunotes.in


Public
● The public access modifier is specified using the keyword public.
● The public access modifier has the widest scope among all other access
modifiers.
● Classes, methods or data members which are declared as public are
accessible from everywhere in the program. There is no restriction on the
scope of a public data members.

PUBLIC

Downloaded from Ktunotes.in


PUBLIC

Downloaded from Ktunotes.in


Access Control

Downloaded from Ktunotes.in


Access Control

Downloaded from Ktunotes.in


Revisiting static keyword
● We access the non-static member of another class using object.
● Syntax is: objectname.member;
● If we want to access a member of another class without using object, then we
have to make it a make it a static member.
● Static class member is independent of any object of that class.
● When a member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object.
● Static member can be accessed using class_name.member;

Remember the syntax of main method

Downloaded from Ktunotes.in


Static method
Methods declared as static(static methods) have several restrictions:

● static methods can only call other static methods.


● static methods must only access static variables.
● static methods cannot refer to this or super keywords.

Initializing member variables.

● Non-static member variables can be initialized using constructor.


● Static members are not part of object, so constructor is not the correct place
to initialize static members.
● How to initialize static members?

Answer is static block


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
static block vs constructor
Static initialization block
● The static blocks are executed at the time of class loading.
● The static blocks are executed before running the main () method.
● The static blocks don't have any name in its prototype.
● If we want any logic that needs to be executed at the time of class loading
that logic needs to placed inside the static block so that it will be executed at
the time of class loading.
Constructor
● A constructor will be executed while creating an object in Java.
● A constructor is called while creating an object of a class.
● The name of a constructor must be always the same name as a class.
● A constructor is executed only during object creation. It executes during each
object creation.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
final keyword
● final keyword is used in different contexts.
● final is a non-access modifier applicable only to a variable, a method or a
class.
● The final modifier is used for finalizing the implementations of classes,
methods, and variables, so that they cannot be changed anymore.
● Following are different contexts where final is used.

Downloaded from Ktunotes.in


final Variables
● A variable can be declared as final by prefixing final keyword.
● The contents of final variables cannot be modified.
● It is a convention to choose uppercase identifiers(CAPITAL LETTERS) for
final variable name. eg. final int TOTAL;
● We can use final variables as if they are constants, their value will not be
changed at any point of time during the program execution.
● Variables declared as final do not occupy memory on a per-instance basis.
● We must initialize a final variable, otherwise compiler will throw compile-time
error.
● A final variable can only be initialized once, either via an initializer or an
assignment statement.

Downloaded from Ktunotes.in


Initializing a final variable
● A final instance variable can be explicitly initialized only once.
● You can initialize a final variable when it is [1] declared. This approach is the
most common.
● A final variable is called blank final variable,if it is not initialized at the time of
declaration.
● Below are the two ways to initialize a blank final variable.
● A blank final variable can be initialized inside [2] constructor.
● If you have more than one constructor in your class then it must be initialized
in all of them, otherwise compile time error will be thrown.
● A blank final variable can be initialized inside [3] initialization block.
● A blank final static variable can be initialized inside a static initialization block.
● A blank final instance variable can be initialized using instance initialization
block
Downloaded from Ktunotes.in
Instance Initialization Block (IIB) in Java
● In a Java program, operations can be performed on
methods, constructors and initialization blocks.
● Instance Initialization Blocks or IIB are used to initialize
instance variables. IIBs are executed before
constructors.
● They run each time when object of the class is
created.
● Initialization blocks are executed whenever the class is
initialized and before constructors are invoked.
● They are typically placed above the constructors within
braces.
● It is not at all necessary to include them in your
classes.

Compare with static initialization block or simple static


block.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Nested Classes
● In Java, just like methods, variables of a class too
can have another class as its member.
● It is possible to define a class within another
class; such classes are known as nested classes.
● The scope of a nested class is bounded by the
scope of its enclosing class(outer).
● Thus, if class B is defined within class A, then B
does not exist independently of A.

Downloaded from Ktunotes.in


Nested Classes
A nested class, that is declared directly within its enclosing class scope, is a
member of its enclosing(outer) class.
class Outer
{
//variables and methods
class Inner
{
//variables and methods
}
}
There are two types of nested classes: static and non-static.

Downloaded from Ktunotes.in


Static nested class
● A static nested class is one that has the static modifier applied.
● It can be accessed by outer class name.
● It can access static data members of outer class including private.
● Static nested class cannot directly access the non-static (instance) data
member or method of the outer class
● It must access the non-static members of its outer class through an object.
● Remember the access restrictions of static method!

Downloaded from Ktunotes.in


Non static class (Inner class)
● A non-static nested class is called inner class.
● Inner class has access to all of the variables and methods of its outer class.
● It may refer to members of its enclosing(outer) class directly in the same way
that other non-static methods of the outer class do.
● No need to create object to access the instance members of the outer class.
● Remember the access conditions of an instance method!

Downloaded from Ktunotes.in


Nested class object creation
● An instance(object) of Inner can be created only within the scope of class Outer.
● We can create an instance of Inner class outside of Outer class by qualifying its
name with Outer classname, as in
● OuterClassNmae.InnerClassName ob=outerObject.new InnerClassName();

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Member inner class and Local inner class
● A non-static nested class declared in the place of a member in the outer class is
known as member inner class
● Inner class has access to all of the variables and methods of its outer class.
● It may refer to members of its enclosing(outer) class directly in the same way
that other non-static methods of the outer class do
Method-local Inner Class
● In Java, we can write a class within a method and this will be a local type. Like
local variables, the scope of the inner class is restricted within the method.
● A method-local inner class can be instantiated only within the method where the
inner class is defined. The following program shows how to use a method-local
inner class.

Downloaded from Ktunotes.in


Anonymous inner class
● An inner class declared without a class name is known as an anonymous inner
class.
● Since they have no name, we have to declare and instantiate them at the same
time, we can't extend them.
● Anonymous classes cannot have explicitly declared constructors.
● They cannot have any static members except for those that are constant.
● Anonymous classes capture local variables that are in the scope of the block in
which we have declared the class.
● Anonymous inner classes are used to create a class by extending a Class or by
implementing an Interface. Syntax is as given below.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Types of inner classes - overview

Downloaded from Ktunotes.in


Command-Line Arguments
● If we want to pass information into a
program when you run it, then you can do
this by passing command-line arguments
to main( ).
● A command-line argument is the
information that follows program’s name on
the command line when it is executed.
● Command-line arguments are stored as
strings in a String array passed to the args
parameter of main( ).
● The first command-line argument is stored
at args[0] the second at args[1] so on.
● In C/C++ args[0] will be the executable
name. Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Variable length arguments
● In Java methods can take a variable number of arguments.
● This feature is called varargs or variable-length arguments.
● A method that takes a variable number of arguments is called a variable-arity
method, or simply a varargs method.
● If the maximum number of arguments is small and known, then we can create
overloaded versions of the method, one for each way the method could be called.
● If the maximum number of potential arguments is larger, or unknowable, then the
arguments can be put into an array, and then the array can be passed to the
method.

Downloaded from Ktunotes.in


Handling variable length arguments
● A variable-length argument is specified by three periods (...)
● E.g. static void test(int ... v) { //statemenst }
● This syntax tells the compiler that test( ) can be called with zero or more
arguments.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Handling variable length arguments
● A method can have “normal” parameters along with a variable-length parameter.
● However, the variable-length parameter must be the last parameter declared by
the method.
● E.g: int test(int a, int b, double c, int ... vals) { //statements } //VALID
● E.g: int test(int a, int b, double c, int ... vals, boolean stopFlag) {} // ERROR!
● We can overload a method that takes a variable-length argument.
● There can be many functions with same name and having different type of
variable length arguments.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Varargs and Ambiguity
● It is possible to create an ambiguous call to an overloaded varargs method.

Downloaded from Ktunotes.in


Varargs and Ambiguity
● Examine following methods
● static void test(int ... v) { // ... }
● static void test(int n, int ... v) { // ... }

If a call test(2); comes, then how it will be treated by the compiler?

Downloaded from Ktunotes.in


Inheritance - Super Class, Sub Class
● Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object.
● 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
● Java does not support multiple inheritance.

Downloaded from Ktunotes.in


Inheritance - Super Class, Sub Class
In below example class A is super class and B is Sub class

Downloaded from Ktunotes.in


The Keyword super
To access parent class members from child class

Downloaded from Ktunotes.in


The Keyword super
To access parent class member variables from child class

Downloaded from Ktunotes.in


The Keyword super
To access parent class member methods from child class

Downloaded from Ktunotes.in


The Keyword super to invoke
parent class constructor

Downloaded from Ktunotes.in


Access Control

Downloaded from Ktunotes.in


protected members in a class
● Variables, methods, and constructors, which are declared protected in a
superclass can be accessed only by the subclasses in other package or any
class within the package of the protected members' class.
● The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.
● Protected access gives the subclass a chance to use the helper method or
variable, while preventing an unrelated class from trying to use it.

Downloaded from Ktunotes.in


Calling order of constructors
In Java, constructor of base class
with no argument gets
automatically called in derived
class constructor.

Downloaded from Ktunotes.in


Calling order of constructors
If we want to call parameterized constructor
of base class, then we can call it using
super(). The point to note is base class
constructor call must be the first line in
derived class constructor.

Downloaded from Ktunotes.in


Constructor chaining
Constructor chaining is the process of
calling one constructor from another
constructor with respect to current object.
Constructor chaining can be done in two
ways:

Within same class: It can be done using


this() keyword for constructors in same
class
From base class: by using super()
keyword to call constructor from the base
class.
Constructor chaining occurs through
inheritance.

Downloaded from Ktunotes.in


Method overriding

Downloaded from Ktunotes.in


Overriding vs overloading

Downloaded from Ktunotes.in


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.

The Object class is beneficial if you want


to refer any object whose type you don't
know. Notice that parent class reference
variable can refer the child class object,
know as upcasting.

Downloaded from Ktunotes.in


Object class methods

Downloaded from Ktunotes.in


Abstract classes and methods
● Programming by contract
● Abstraction is a design level activity whereas encapsulation is implementation
level
● Data abstraction is the process of hiding certain details and showing only
essential information to the user.
● Abstraction can be achieved with either abstract classes or interfaces
(Interface - which you will learn more about in the next chapter).
● Ways to achieve Abstraction
● There are two ways to achieve abstraction in java
● Abstract class (0 to 100%)
● Interface (100%)

Downloaded from Ktunotes.in


Abstract classes and methods
● The abstract keyword is a non-access modifier, used for classes and
methods:
● Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
● Abstract method: can only be used in an abstract class, and it does not have
a body. The body is provided by the subclass (inherited from).

Downloaded from Ktunotes.in


Abstract classes
● A class which is declared as abstract is known
as an abstract class.
● Points to Remember
● An abstract class must be declared with an
abstract keyword.
● It can have abstract and non-abstract
methods.
● It cannot be instantiated.
● It can have constructors and static methods
also.
● It can have final methods which will force the
subclass not to change the body of the
method.
Downloaded from Ktunotes.in
Abstract classes
abstract class Vehicle
{
public abstract void start();
public abstract void gearShift();
}
class ElectricCarAT extends Vehicle
{
public void start(){ }

public void gearShift(){ }

Downloaded from Ktunotes.in


final keyword and inheritance
Using final to Prevent Overriding - final methid

When a method is declared as final then it cannot be overridden by subclasses.

When a class is declared as final then it cannot be subclassed i.e. no any other
class can extend it

Downloaded from Ktunotes.in


final class
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}

Downloaded from Ktunotes.in


final method
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}

Downloaded from Ktunotes.in


References
● Herbert Schildt, Java: The Complete Reference, 8/e, Tata McGraw Hill, 2011.

● Visual Paradigm - www.visual-paradigm.com

● GeeksforGeeks - www.geeksforgeeks.org

● Wikipedia - www.wikipedia.org

● Tutorialspoint - www.tutorialspoint.com

● Java Zone - https://dzone.com


Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the
respective content creators. Document is compiled exclusively for study purpose and shall not be used for
commercial purpose.

Downloaded from Ktunotes.in

You might also like