Java Notes
Java Notes
Java Notes
Java is a 3rd Generation Object Oriented programming Language, developed by James Gosling in the year 1995. It was
initially codenamed as Green and hypothetically called Oak named after the Oak tree outside Gosling’s house.
It is case sensitive and has a unique two step translation process that includes both Compilation and Interpretation which
makes Java Platform independent.
Drawbacks of POP
1) As Data values are global to all the functions, you may require making necessary changes in the functions due to change
in the data values.
2) It is not suitable to solve complex problems in real situations.
Features of OOP
1. It gives equal stress on data and function.
2. It makes the program simple by dividing it into a number of objects.
3. The objects can be used as a bridge to have data flow from one function to another.
4. Data can be easily modified without any change in the function.
Advantages of OOP
1) We can extend the use of existing class through inheritance.
2) Using the concept data hiding can generate secured program.
3) We can create different modules in our project through objects.
4) Multiple instances of an object can be generated to co-exist without any interference.
5) It is highly beneficial to solve complex problems.
6) It is easy to modified and maintain software complexity.
Examples of OOP based languages are Simula, C++, Java, Python, and Smalltalk etc…
Attribute:-The characteristics which make every object having its identity make them distinguished is called attribute.
Behaviour – The behaviour of any class or object is represented through various functions and methods.
Message Passing – When object need to interact with one another they do so by passing information to and from one
another, this is called Message Passing
Data Hiding – is the data which cannot be accessed directly outside, class premises although they are available in the
same program
Garbage Collection – The Garbage-collected Heap is where the objects in Java programs are stored. Whenever we
allocate an object using new operator, the heap comes into picture and memory is allocated from there. Java does this
automatically using Garbage collection mechanism, using an algorithm named Mark & Sweep logic. Remember that the local
object reference resides on Stack but the actual object resides in Heap only. Also, arrays in Java are objects, hence they
also resides in Garbage-collected Heap.
Object Code – The interpreter of Java named JVM (which stands for Java Virtual Machine) then converts the intermediate
Byte Code into machine specific executable which runs on the host machine.
API (Application Programming Interface) – consists of libraries of pre compiled code that programmers can use in their
application and programs for designing softwares. Hence we can say that Java API consists of functions and variables that
programmers can reuse.
Java Packages – Packages are collection of similar nature classes. A package can be created by using the keyword
‘package’ and the keyword used to include a package in our program is ‘import’. Java contains an extensive library of pre-
written classes grouped together into packages –
java.lang.* It is a default package containing String, Math, Integer, thread etc.
java.io.* It is the basic Input Output package of Java
java.util.* The java utility package
java.applet.* The applet package
java.net.* The Networking package of Java
java.awt.* It stands for Abstract Windows Toolkit, for designing Windows based applications.
Basic Features of Java:-
1) Write once run anywhere(WORA)
2) Platform Independent
3) Offers many security features to make its program safe and secure
4) Built in graphics & supports multimedia
5) Light Weight code
6) Open Product… i.e., freely available to all.
Blue – J
Blue-J is an Integrated Development Environment (IDE) for writing, editing, compiling, testing, executing and
debugging the Java programming language, developed mainly for educational purposes, but also suitable for small-scale
software development. Blue J was initially designed at University of Kent by David Barns and Michael Kollins
The main screen graphically shows the class structure of an application under development (in an UML-like diagram), and
objects can be interactively created and tested. This interaction facility, combined with a clean, simple user interface, allows
easy experimentation with objects under development.
Features of Blue – J
1. Simplicity of the interface – The GUI user friendly interface is simpler than in full-scale professional environments, and
thus easier to learn.
2. The “Code Pad” – The code pad is a tool that instantly evaluates arbitrary Java expressions and statements.
3. Regression testing
4. Provision for syntax highlighting
5. Built in debugger.
6. Program input/output i.e. In Blue-J both the parameter values for and the return values from method calls can be
entered / inspected directly.
7. Java ME support – Java ME (Micro Edition) projects can be developed and deployed from Blue-J.
Keywords are the reserved words which convey a special meaning to a language compiler. They can not be used for any
other purpose like function name, variable name or object names.
There are around 48 keywords, of which const and goto have been reserved even though they are not currently being used
for any purpose true, false and null might appear to be keywords but actually they are literals, and hence are reserved
words.
Identifiers are fundamental building blocks of a program. They are named memory locations or simply names given to
variables, objects, classes, functions, arrays etc… They are case sensitive.
There are certain Identifier naming rules –
1. They can consist of infinite number of alphabets and digits
2. They must start with an alphabet and not with a digit
3. They can not be a keyword or reserved word
4. They cannot have any spaces
5. They cannot contain any special character other than _(underscore), $(dollar)
While naming identifiers there are certain conventions that make them identifiable
1. Class names begins with an Uppercase character
2. Identifiers having multiple words, the first character of 2nd and subsequent words are in Uppercase
3. Constants are in all CAPITALS
Comments (Remarks):- refers to statements which are ignored by the java compiler and increase the readability of a
program. These are used to state a purpose of the instructions used in a program.
Literal are the fixed values that are assigned to variables which do not change its values during program execution. They
are of 5 types –
1.Integer Literal
i.Decimal
ii.Octal
iii.Hexadecimal
To represent Decimal Integers we simply use the integer type number as literal, e.g. int p = 45; So, System.out.println (p); //
Shows 45 as output
To represent Octal Integers however we precede the number with a 0 (zero) as literal, e.g. int p =
045; System.out.println (p); // Shows 37 as output coz, (45) in octal is 37 in decimal number system.
Moreover to represent any Hexadecimal Integer we use 0x (Zero and lowercase letter x) preceding the number as
hexadecimal literal e.g. int p = 0x45;
System.out.println (p); // Shows 69 as output coz, (45) in hexadecimal is 69 in decimal number system.
2. Real Literals
i. Floating point literals have 7 digits of precision after the decimal point
ii. Double literals have 16 digits of precision after decimal point
5. Null Literal
Operator – are the entities or symbols that tell the compiler that what operation has to be performed with one, two or three
number of operands within a given expression.
There are approximately a set of 37 different operators that Java uses
Operators can either operate on 1, 2 or 3 operands and accordingly named as –
Data types – are the entities that tell the compiler that which variable will hold what kind of values.
Primitive data types – Also called as Basic Data type. They are pre defined or built in data types because they are already
built in java. E.g. byte, short, int, long, float, double, char, boolean.
Non Primitive Data Types: Directly or indirectly dependent on primitive data types. They store the data values with
reference to the address or locations. So, they are called as Reference Data Types. E.g. array, classes interfaces etc…
Range, Size and hierarchy of various primitive data types
Type ….Size…. Range
boolean 1 byte (uses 1 bit) true and false
byte 8 bits (1 bytes) – 128 to + 127
char 16 bits (2 bytes) 0 to 65,535
short 16 bits (2 bytes) – 32768 to +32767
int 32 bits (4bytes) – 2 31 to + 231 – 1
long 64 bits (8bytes) – 2 63 to + 263 – 1
float 32 bits (4bytes) – 3.4E+38 to +3.4E+38
double 64 bits (8bytes) – 1.7E +308 to 1.7E+308
Type conversion The process of convert one primitive datatype to another either from lower precision to higher or vice
versa I known as type conversion. This can be achieved in two ways –
Implicit Data Type Conversion – Such Type of conversion is performed by the compiler without programmer’s
intervention. In this type of conversion a datatype of lower precision gets converted to a datatype with higher precision.
e.g. int a = 10;
double d = a;
System.out.println(d);
The above code snippet gives 10.0 as output; this clearly indicates that the int datatype got automatically converted to
double.
Explicit data type Conversion – Such type of conversion is user defined conversion which forces an expression to be
converted into specific type. Generally this is done to force a conversion from higher precision data type to lower.
e.g. double pi = 3.1415;
int i = pi;
The above statement is considered illegal and hence gives an ERROR message “POSSIBLE LOSS OF PRECISION”
Hence the above code should be Type Casted in the following manner –
int i = (int) pi;
System.out.println(i);
Now, the output to the above code will be 3
Potential problems with Type Casting
1. When a datatype is converted from double to float results in loss of precision i.e. a double datatype has 16 digits after
decimal point which gets truncated to 7 digits.
2. When a datatype is converted from double or float to integer type results in loss of entire fractional part leaving behind
only the integral part.
3. When a higher order integer datatype like int or long is converted to byte or short might result in the data going out of
range.
Take an example
int a = 130;
byte b = (byte) a;
System.out.println(b);
The output for the above code is – 126
Operators in Java
Operator – are the entities or symbols that tell the compiler that what operation has to be performed with one, two or
three number of operands within a given expression.
There are approximately a set of 37 different operators that Java uses
1. Arithmetic Operators (+ , – , * , / , %)
2. Relational Operators (> , < , >= , <= , == , !=)
3. Logical Operators (&&, || , !)
4. Conditional Operators (? : )
5. Bitwise Operators (&, | , ~ , ^)
6. Shift Operators (>> , << )
7. Special Operators (this , dot (.) , new, (type) , instanceOf )
Shortcut Operations in Java
Java implements shortcut methods to work with basic arithmetic operators like
+, – , * , / and %
Similarly we have –
Subtraction Assignment – =
Multiplication Assignment *=
Division Assignment /=
Modulus Assignment %=
Unary Operators
a = a + 1 can also be written as either a++ (Post Increment) or ++a (Pre Increment)
int a = 5;
System.out.println(a++);
Gives 5 as output as the value of ‘a’ is first used and then increased to 6, so if we have one more print statement after the
above stated line will give 6 as output.
System.out.println(a); // Output is 6
In a Prefix operator like Pre Increment or Pre Decrement the value of the operand is first increased or decreased as the
case may be and then used for e.g.
int a = 5;
System.out.println(++a);
Gives 6 as output as the value of ‘a’ is first incremented and then displayed.
Relational Operators are used to find the relationship between two quantities, whether they are equal, un-equal, greater
than less than etc…
Symbol Relationship
== Equal to
!= Not equal to
Logical Operators are used to join 2 or more relational operators and of 3 types –
1. && (and) returns true when both or all the relations are true
2. || (or) returns true when any one of the relations are true
3. ! (not) inverts true to false and false to true
Say if the value of a=4, b=6 then…
if(a>5 && b>5) will return false coz both the conditions are not true
if(a>5 || b>5) will return true coz one of the conditions is true
It is not mandatory to have a relation always inside an ‘if’, even without any ‘if’ clause we can check the return of any
relation like –
System.out.println(x==7); will give the output as true, and if we place (!) in front of the relation, System.out.println( ! (x==7));
will invert the output from true to false.
Bitwise and Shift Operators
xor 1 if two bits are different and 0 in all other cases 3^5 6
a ^ b
not Inverts the bits, after transforming the entire number into full bit representation ~3 -4
~a
left shift Shifts the bits of n towards left by p positions thereby adding Zeros to the extreme LHS 3 << 2 12
n << p
right shift Shifts the bits of n towards right by p positions resulting in loss of bits from LHS 5 >> 2 1
n >> p
In all the above examples the operands (values) must be converted to Binary and then implemented with
respective operators except for Right and Left Shift operators where only the variable ‘n’ is converted to
binary and not ‘p’
Don’t confuse &&, which is the logical and, with &, which is the uncommon bitwise and. Although the bitwise and can
also be used with boolean operands, this is extremely rare and is almost always a programming error.
Conditional Operator
The only Ternary operator of Java is the Conditional Operator, ? : which can be used as an alternative to if…else
Syntax: variable = condition ? true : false ;
In the above code the value of ‘n’ becomes 1 as the condition 100>50 is true, had it been wrong the value of ‘n’ would
have been 0;
Special Operators
q [ ] this operator is used to assign the size for an array and to access any particular element within an array.
q ( ) the parenthesis operator is used to enclose the arguments to a function in the function prototype line and invoke a
function by enclosing the list of arguments.
q Dot (.) the dot operator is used to access the instance/class members of a class through an object or class name.
q new – the new operator is used to assign and allocate memory to new objects and arrays.
q instanceof – this operator checks whether the first argument is an instance of the second argument or not.
e.g. str instanceof String // will return true if str is a String variable
Precedence Table
Operator Precedence
2
Math.cos(r) Returns cosine of angle ‘r’ given in radians
3
Math.tan(r) Returns tangent of angle ‘r’ given in radians
4
Math.asin(x) Returns the angle in radians whose sine value is ‘x’
5
Math.acos(x) Returns the angle in radians whose cosine value is ‘x’
6
Math.atan(x) Returns the angle in radians whose tangent value is ‘x’
7
Math.toDegrees(r) Converts Radians to Degrees
8
Math.toRadians(d) Converts Degrees to Radians
9
Math.min(a, b) Returns the smaller among a and b
10
Math.max(a, b) Returns the larger among a and b
11
Math.abs(a) Convert -ve magnitude to +ve magnitude.
12
Math.sqrt(x) Returns the square root of ‘x’
13
Math.pow(x, y) Returns x to the power of y
14
Math.exp(x) Returns ‘e’ to the power of ‘x’ where e=2.718 called Euler’s Constant just like pi
15
Math.cbrt(x) Returns the cube root of ‘x’
16
Math.log(x) Returns the Natural logarithm of ‘x’
17
Returns the integral value of x less than or equal to ‘x’ but datatype returned is double,
Math.floor(x)
hence Math.floor(7.9) will give 7.0
18
Returns the integral value of x greater than or equal to ‘x’ but datatype returned is double,
Math.ceil(x)
hence Math.ceil(7.9) will give 8.0
19
Returns the integral value of x by rounding off the fractional part to the nearest integer , but
Math.rint(x)
data type returned is double, hence Math.rint(7.9) will give 8.0
20
Returns the integral value of x by rounding off the fractional part to the nearest integer, but
Math.round(x)
datatype returned is int, hence Math.round(7.9) will give 8
21
Math.random() Generates a double type random number between 0 to 1
22
Math.PI This returns the 16 digits precise value of PI(Note that it is not a function)
1. Syntax Errors – A Syntax error occurs when the programmer writes a grammatically incorrect code that does not
support the rules of programming of that particular language. This type of error gets detected by the compiler. E.g. missing
semicolon, using keywords as identifier name, unmatched pair of { }, undefined functions, undeclared and un-initialized
variables etc…
2. Logical Errors – A Logical error is born out of a programmer who misunderstands the logic of the program and writes a
syntactically correct code but which does not comply to the algorithm of the problem. E.g. The program demanded squaring
of an integer type number but the programmer writes a code that determines the square root of the number.
3. Runtime Errors – A Runtime error is shown when a syntactically and logically correct program with a set of inputs
which is invalid for a given expression. The same expression is valid for another set of values. E.g. int quo = div / n, the
expression is valid for all sets of positive values of n but not if n = 0.
Common Errors
0 < x < 100
Comparison operators can be used with two numbers. Although you can write 0 < x = or <= instead of ==. For example,
because the decimal number 0.1 can not be represented exactly in binary, (0.1 + 0.1 + 0.1) is not equal to 0.3
Always make sure that the number of if clause should not exceed the number of else clause, because it will result in
‘dangling else problem’, in such case make use of if…else if…else construct as shown below –
if (condition 1)
{
… // Do this clause if the condition is true
}
else if (condition 2)
{
… // Do this clause if the condition is false
}
else
{
… // Do this clause if the condition is false
}
switch…case Statement
The if statement allows you to select one of two sections of code to execute based on a boolean value (only two possible
values). The switch statement allows you to choose from many statements based on an integer (including char)
switch (expr)
{
case c1: … break;
case c2: … break;
…
default:
}
switch
The switch keyword is followed by a parenthesized integer expression, which is followed by the cases, all enclosed in
braces.. The switch statement executes the case corresponding to the value of the expression. Normally the code in a case
clause ends with a break statement, which exits the switch statement and continues with the statement following the
switch. If there is no corresponding case value, the default clause is executed. If no case matched and there is no default
clause, execution continues after the end of the switch statement.
case
The case keyword is followed by an integer constant and a colon. This begins the statements that are executed when the
switch expression has that case value.
default
If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of
the “else” for the switch statement. It is written after the last case be convention, and typically isn’t followed by break
because execution just continues out the bottom of switch if this is the last clause.
break
The break statement causes execution to exit to the statement after the end of the switch. If there is no break, execution
falls through into the next case. Flowing directly into the next case is almost always an error.
A switch statement can often be rewritten as a substitute for ‘if’ statement in a straightforward manner. For example, the
preceding switch statement could be written as follows. When one of a number of blocks of code is selected based on a
single value, the switch statement is generally easier to read. The choice of if or switch should be based on which is more
readable.
• No ranges. It doesn’t allow ranges, eg case 90-100:. Many other languages do.
• Integers only. It requires integers and doesn’t allow useful types like String. Many other languages do.
• Error-prone. It is error-prone and a common source of bugs – forgetting break or default silently ignores errors. Some
languages have eliminated these dangerous situations.
• Fall through. Another disadvantage of switch…case is that in absence of break statement in the respective cases will cause
the flow control to cascade down and execute all the cases that does not contain ‘break’ statements until it reaches end of
switch or a case that implements a break. This is called fall through.
Iteration through Loops
The purpose of loop or iterative statements is to repeat a block of Java statements several times depending upon the
condition mentioned within the loop. There are two kinds of looping statements in Java.
1. Entry Controlled Loop
2. Exit Controlled
An Entry Controlled loop which is also known as Pre Tested Loop the condition of the loop is first checked and then the
loop body is executed, which means if the condition is false the loop doesn’t get executed even for once.
E.g. a. for LOOP
b. while LOOP
An Exit Controlled loop which is also known as Post Tested Loop the condition is checked at the end of the loop body,
which means even if the condition is false the loop gets executed at least for once.
E.g. a. do…while LOOP
If the body of a loop has more than one statement, you must put the statements inside braces. If there is only one
statement, it is not necessary to use braces { }. However, many programmers think it is a good idea to always use braces
to indicate the scope of statements. Always using braces allows the reader to relax and not worry about the special single
statement case.
while statement
The while statement is used to repeat a block of statements while some condition is true. The condition must become false
somewhere in the loop, otherwise it will never terminate.
Syntax:
initialization;
while (condition)
{
Body;
update;
}
//… While loop to display squares of natural nos. less than 10
int i = 1;
while (i <=10)
{
System.out.println(i*i);
i++;
}
for statement
Many loops consist of three operations surrounding the body:
(1) initialization of a variable,
(2) testing a condition, and
(3) updating a value before the next iteration.
The for loop groups these three common parts together into one statement, making it more readable and less error-prone
than the equivalent while loop. For repeating code a known number of times, the for loop is the right choice.
Functions in Java
A function is a block or portion of code within a larger program which consists of some declarations and executable
statements, which performs a specific task and is relatively independent of the remaining code.
The term method is used alternatively with function and means the same in Java programming language. A larger block of
code is broken down into smaller and simpler modules called ‘member methods’ this is how the OOP language Java
implements ‘Modularity’.
Anatomy of a function
FUNCTION NAME ( )
{
Body of the function…
}
2. These are keywords which redefines the functionality within the methods. They can be final, native, static, synchronized,
transient, volatile etc…
3. They specify what type of value a function can return, hence they can be of any primitive of reference data types like int,
byte, float, char, String or even class types. In case the function doesn’t return any value the keyword ‘void’ is used.
4. Function name – This can be any valid identifier, but it is always advisable to take logical and meaningful names, it
should conventionally begin with a lowercase letter and in case of multiple words join the words and begin each word in
Uppercase except for the first word.
e.g. toUpperCase( )
5. This is a comma separated list of variables along with associated data types. This list can also be empty which indicates
the function is non–argumentative.
e.g.
public static void add(int a, int b)
{
…
}
Function prototype
The first line of a function that consists of access specifier, modifier, return type, function name and list of parameters
enclosed within a pair of parenthesis is called function prototype.
A function prototype describes the function interface to the compiler, by giving details of number and type of arguments,
return type etc…
e.g.
public static void compute(int a, int b)
{
…
…
}
Function signature
The function signature is a part of function prototype; it basically refers to the argument list i.e. number, order and type of
arguments.
e.g.
public static void compute(int a, int b)
{
…
…
}
Public members are accessible everywhere, within the same class as well as inside other classes that inherits the base class
or by creating objects of the former class in the latter one even if they do not inherit, but private members are accessible
only within the same class.
obj1.x=10;
obj2.x=20; // the same variable ‘x’ has three different values simultaneously
obj3.x=30;
y = 100; // the variable ‘y’ being static is accessed directly and can have only
// one value
obj1.y=100;
obj2.y=200; // even if we try to access the variable ‘y’ through different objects
obj3.y=300; // the same ‘y’ gets overwritten and finally the last value prevails
}}
So, we see that if a member is static in nature it will have only one copy in the physical memory of the computer, which can
be accessed directly without the need of creating objects. But if it is non-static then we need to create objects to specify
which instance we are referring to as it has multiple occurrences.
The formal parameters are those that appear at the point of function declaration or function signature are called Formal
parameters.
e.g.
public static void main( )
{
int x = 10, y = 20;
add (x, y); actual parameters
}
1. Computational functions – The functions that computes or calculates certain values or quantities and returns the
answer to the calling method is called Computational function.
e.g. Math.pow(a,b);
2. Manipulative functions – The functions which manipulates the data and returns information to the calling function as
success or failure code in the form of 0 & 1 or true & false.
e.g. Character.isLetter( )
3. Procedural Functions – The functions that perform certain tasks like reading from source files, reading from terminals,
displaying data to the terminal are called procedural functions. They generally do not have any return type.
e.g. System.out.println( );
Pure & Impure functions
A pure function is one that takes objects and/or primitive data as arguments but does not modify the objects hence the
return value of such functions are either primitive data or an entirely new object created inside the function. They are also
known as Accessor methods.
An impure function on the other hand modifies the state of its objects or arguments. They are also known as Modifier
methods.
e.g.
class Overload
{
public static void area(int s)
{
System.out.println(“Area of square =” + (s*s));
}
public static void area(int l, int b)
{
System.out.println(“Area of rectangle =” + (l*b));
}
public static void area(double r)
{
System.out.println(“Area of circle =” + (3.1415 * r * r));
}
}
Constructors in Java
A Constructor is a member method of a class which has same name as that of a class; has no return type not even void, used to initialize
the instance variables of a class, and gets invoked automatically as soon as the object of the class is created.
class Constr
{
int n;
Constr( )
{
n = 0;
} // invokes the constructor
A parameterized constructor accepts parameters or values in its argument list which initialize the various instance data
members of the class.
class Constr
{
int n;
Constr(int val)
{
n = val;
} // invokes the constructor
Exception Handling
An exception in general is any unexpected / contradictory situation of error encountered at the time of program execution is
called an Exception.
Types of Errors
1. Compile time errors / Syntax Errors – The errors that occurs as a result of violating the programming rules or syntax are called
Compile time errors. They get detected at the time of program compilation.
e.g. int class = 10; // class is a keyword hence syntactically incorrect
1. Run time errors – The errors that occurs during program execution is called run time errors. These unexpected errors may occur due
to array index going out of bound, end of file reached, type mismatch errors at the time of data input etc…
1. Logical Errors – These errors are those which occur due to misinterpretation of the problem / program logic, resulting in design of
wrong code by the programmer. Such errors are very difficult to detect, like if the problem says to add two numbers and find their sum
and the programmer commits a multiplication on the numbers, such programs might be syntactically totally correct but the logic was
misinterpreted.
Exception handling is a transparent and an efficient way of handling run time errors.
Try block contains the code which might lead to run time errors.
Catch block contains the code to deal with an exception that might arouse due to execution of a try block.
Finally block contains the code that gets executed when no other block is able to handle the exception.
Throws is a keyword which is used to inform that an error has occurred, it is specified in the line of function definition
(prototype).
class Error
{
public void testfunction (int x, int y) throws Exception
{
int z;
try
{
z = x / y;
System.out.println( z );
}
catch (exception exp)
{
System.out.println(exp.getMessage( ) );
}
finally
{
System.out.println(“Un–reported exception has occurred…”);
}
}
Wrapper Classes
Java is an object-oriented language and as said everything in java is an object. What about the primitives datatypes? As a solution to this
problem, Java allows you to include the primitive datatypes in the family of objects by using what are called wrapper classes.
To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for
objects, like as being added to Collections, or returned from a method with an object return value.
To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting
primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as
binary, octal, and hexadecimal.
Wrapper Class functions / methods
The wrapper class methods that are static in nature can be directly accessed as –
Function Description
Function Description
Function Description
Function Description
Function Description
Function Description
Function Description
A String is a collection of characters, in Java String is not a primitive datatype instead is implemented as a class. In Java a String is an
immutable object which means it can not be modified. For understanding this we can take a small example of a String class function
concat( ) which is used to join two strings.
String s1 = “Computer”;
As a String Literal
As a String object
A String Literal can be created as follows –
Each time a String literal is created JVM checks the String Constant Pool if the String exists in the pool them no new string will be
created instead a reference to the pool is returned.
e.g.
String str2 = “Welcome”; // no new string is created as “Welcome” already exists in pool
A String Object can be created using a new keyword –
In such cases Java will create the String in the Heap Memory
String handling is a way of manipulating strings / string literals / string objects by concatenating strings, comparing strings, extracting
characters from string, creating substrings from given strings, replacing characters from within a string, etc…
1 length( ) int
Returns length of a string
2 charAt(k) char
Returns a character at a position k within the string.
3 toUpperCase( ) String
Returns a String which has all the letters in Capitals (uppercase)
4 toLowerCase( ) String
Returns a String which has all the letters in Small Letters
(lowercase)
5 startsWith(s) boolean
Returns true if string starts with a string s
6 startsWith(s, k) boolean
Returns true if string starts with a string s at index k
7 endsWith(s) boolean
Returns true if string ends with a string s
8 endsWith(s) boolean
Returns true if string ends with a string s starting at an index k
9 indexOf(s) int
Returns an index of the first occurrence of String s in string
10 indexOf(s, k) int
Returns an index of String s starting an index k in string
11 lastIndexOf(s) int
Returns an index of the last occurrence of String s in string
12 substring(k, n) String
Returns a substring from index k to index n-1 of string
13 substring(k) String
Returns a substring from index k to the end of string
14 concat( ) String
Joins two strings
15 trim( ) String
Returns a String which has all the spaces removed from the
beginning and end without altering any intermediate spaces.
16 equals(s) boolean
Returns true if the two strings have equal values
17 equalsIgnoreCase(s) boolean
Same as above ignoring case
18 compareTo(s) boolean
Compares two strings
19 compareToIgnoreCase(t) boolean
Same as above ignoring case
Declaring an array is the same way of declaring a variable but with extra square brackets to inform the compiler, that the variable
represents an array. Array size should be given at the time of creation. Depending upon the size, continuous memory locations are
allocated to the elements. Array identifier follows the same rules of Java identifiers.
} // closing class
Application of Arrays
Arrays are broadly used in storing huge list of similar data as they are easy to implement under a single name. And are used for –
1. Searching
o Linear Search
o Binary Search
2.Sorting
o Bubble Sort
o Exchange Selection Sort
o Quick Sort
o Merge Sort
3. Merging Arrays
o Alternate Merge
o End to end Merge
o Similar & Dissimilar sized arrays
Inheritance
Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or acquire the properties
and methods of other classes. A class derived from another class is called a subclass, whereas the class from which a subclass is derived
is called a superclass.
Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.
The keyword “extends” is used to derive a subclass from the superclass, as illustrated by the following syntax:
However, you didn’t have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and
had taken substantial time to debug.
Types of Inheritance
Single Inheritance –
A subclass that has only one superclass is a case of single inheritance.
Multilevel Inheritance –
Classes can be derived from classes that are derived from other classes that are derived from again other classes, and so on, ultimately
derived from the topmost class that’s multilevel inheritance.
Multiple Inheritance
When a sub class derives from two or more super class, such an inheritance form is called multiple but in Java it can not be achieved
directly and is implemented through Interface.
Hierarchical Inheritance –
A superclass having one or more subclasses is a case of hierarchical inheritance.
Hybrid Inheritance –
A combination of two or more of the above forms of Inheritance is called Hybrid Inheritance.
Access Specifier
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class
available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you
to control access to classes, methods, and fields via so-called access specifiers.
Java offers four access specifiers, listed below in decreasing accessibility:
• public
• protected
• default (no specifier)
• private
We look at these access specifiers in more detail.
Public
Public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only
contain one public class whose name must also match with the filename. You use public classes, methods, or fields only if you explicitly
want to offer access to these entities and if this access cannot do any harm. An example of a square determined by the position of its
upper-left corner and its size.
public class Square
{ // public class
public x, y, size; // public instance variables
}
Protected
Protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses,
and within classes of the same package, but not from anywhere else. You use the protected access level when it is appropriate for a
class’s subclasses to have access to the method or field, but not for unrelated classes.
Default (no specifier) also known as friendly
If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the
class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages.
Private
Private methods and fields can only be accessed within the same class to which the methods and fields belong. Private methods and
fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access
specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided.
An example, in which the position of the upper-left corner of a square can be set or obtained by accessor methods, but individual
coordinates are not accessible to the user.
public class Square
{ // public class
private double x, y // private (encapsulated) instance variables
public getCorner()
{ // setting values of private fields
return Point(x, y);
}
}
The following table summarizes the access level permitted by each specifier.
Situation public protected default private
Accessible to other class from same package? yes yes yes no
Accessible to classes from different package? yes no, unless it is a subclass no no