Professional Documents
Culture Documents
Returns a String object representing the specified Returns a String which has all the
toString( ) 3 toUpperCase( ) String
character as a single character string. letters in Capitals (uppercase)
e.g. char ch = ‘A’; Returns a String which has all the
4 toLowerCase( ) String
System.out.println(Character.isLetter(ch)); // returns true letters in Small Letters (lowercase)
System.out.println(Character.toLowerCase(ch)); // returns a
Returns true if string starts with a
5 startsWith(s) boolean
string s
>String Handling in Java
A String is a collection of characters, in Java String is not a primitive datatype Returns true if string starts with a
6 startsWith(s, k) boolean
instead is implemented as a class. In Java a String is an immutable object which string s at index k
means it can not be modified. For understanding this we can take a small example
Returns true if string ends with a
of a String class function concat( ) which is used to join two strings. 7 endsWith(s) boolean
string s
String s1 = “Computer”;
Returns true if string ends with a Declaring, Assigning and Accessing the Array
8 endsWith(s) boolean The following program explains the basic syntax of creating an array in Java. First an
string s starting at an index k
integer array by name, marks, is created which is filled with zero values by default.
Returns an index of the first Creating sized arrays
9 indexOf(s) int
occurrence of String s in string Syntax:
datatype array_name[ ] = new datatype[size];
Returns an index of String s
10 indexOf(s, k) int Example:
starting an index k in string
int ARR[ ] = new int[5];
Returns an index of the last By default all array elements are initialized to ‘zero’.
11 lastIndexOf(s) int
occurrence of String s in string
Creating un-sized array
Returns a substring from index k to
12 substring(k, n) String Syntax:
index n-1 of string
datatype array_name[ ];
Returns a substring from index k to Example:
13 substring(k) String
the end of string int ARR[ ];
But such arrays need to be sized later to use them,
14 concat( ) String Joins two strings arrayname = new datatype[size]; // make sure to use the base address only
Returns a String which has all the without[ ]
spaces removed from the Example:
15 trim( ) String ARR = new int[5];
beginning and end without altering
any intermediate spaces.
Un-sized array with assignment
Returns true if the two strings have datatype array_name[ ] = {value1, value2, value3,… value};
16 equals(s) boolean
equal values make sure the [ ] remains empty.
17 equalsIgnoreCase(s) boolean Same as above ignoring case Example:
int ARR[ ] = {1,2,3,4,5};
18 compareTo(s) boolean Compares two strings Sample Program implementing a Single Dimensional Array
19 compareToIgnoreCase(t) boolean Same as above ignoring case
public class ArrayTest1
{
public static void main(String args[])
>Single and Double Dimensional Arrays in Java {
Definition of One Dimensional Array int marks[] = new int[5];
One dimensional array is a list of variables of same datatype that are accessed by a System.out.println(“Elements are ” + marks.length);
common name. An individual variable in the array is called an array element. The for(int j=0;j<marks.length;j++)
locations in which they are stored is called array index or array subscript hence {
arrays are also sometimes referred as Subscripted variables. System.out.println(“Default value: ” + marks[j]);
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 // Now assign values
should be given at the time of creation. Depending upon the size, continuous marks[0] = 50;
memory locations are allocated to the elements. Array identifier follows the same marks[1] = 60;
rules of Java identifiers. marks[2] = 70;
marks[3] = 80; Classes can be derived from classes that are derived from other classes that are
marks[4] = 90; derived from again other classes, and so on, ultimately derived from the topmost
System.out.println(“Value of 1st element: ” + marks[0]); class that’s multilevel inheritance.
System.out.println(“\nPrint the values in a single row”); Object. Such a class is said to be descended from all the classes in the inheritance
for(int i = 0; i < marks.length; i++) chain stretching back to Object.
{ The keyword “extends” is used to derive a subclass from the superclass, as
System.out.print(marks[i] + “\t”); illustrated by the following syntax:
}
// Alternative method of printing supported from JDK 1.5 class Name_of_subclass extends Name_of superclass
for(int k : marks) {
{ //new fields and methods that would define the subclass go here
System.out.print(k + “\t”); }
} Example Code of Inheritance
} //closing main() public class Bicycle
} // closing class {
// the Bicycle class has three fields
Application of Arrays public int cadence;
Arrays are broadly used in storing huge list of similar data as they are easy to public int gear;
implement under a single name. And are used for – public int speed;
1. Searching // the Bicycle class has one constructor
o Linear Search public Bicycle(int startCadence, int startSpeed, int startGear)
o Binary Search {
2.Sorting gear = startGear;
o Bubble Sort cadence = startCadence;
o Exchange Selection Sort speed = startSpeed; }
o Quick Sort <NOT IN SYALLABUS> // the Bicycle class has four methods
o Merge Sort <NOT IN SYALLABUS> public void setCadence(int newValue)
3. Merging Arrays <YOUR CHOICE> {
o Alternate Merge cadence = newValue;
o End to end Merge }
o Similar & Dissimilar sized arrays public void setGear(int newValue)
{
>Inheritance gear = newValue;
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 public void applyBrake(int decrement)
class derived from another class is called a subclass, whereas the class from which a {
subclass is derived is called a superclass. speed – = decrement;
A subclass that has only one superclass is a case of single inheritance. }
Whereas a superclass having one or more subclasses is a case of hierarchical public void speedUp(int increment)
inheritance. {
speed += increment;
}
}
A class declaration for a MountainBike (subclass) that inherits Bicycle (superclass): >Access Specifier
public class MountainBike extends Bicycle 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
// the MountainBike subclass adds one field this way the chance of making accidental mistakes in changing values is minimized.
public int seatHeight; Java allows you to control access to classes, methods, and fields via so-called access
// the MountainBike subclass has one constructor specifiers.
public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) Java offers four access specifiers, listed below in decreasing accessibility:
{ • public
super(startCadence, startSpeed, startGear); • protected
seatHeight = startHeight; • default (no specifier)
} • private
// the MountainBike subclass adds one method We look at these access specifiers in more detail.
public void setHeight(int newValue) #Public
{ Public classes, methods, and fields can be accessed from everywhere. The only
seatHeight = newValue; 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
MountainBike inherits all the fields and methods of Bicycle and adds the field upper-left corner and its size.
seatHeight and a method to set it. Except for the constructor, it is as if you had
written a new MountainBike class entirely from scratch, with four fields and five public class Square
methods. { // public class
However, you didn’t have to do all the work. This would be especially valuable if the public x, y, size; // public instance variables
methods in the Bicycle class were complex and had taken substantial time to debug. }
Types of Inheritance
Single Inheritance – #Protected
A subclass that has only one superclass is a case of single inheritance. Protected methods and fields can only be accessed within the same class to which
Multilevel Inheritance – the methods and fields belong, within its subclasses, and within classes of the same
Classes can be derived from classes that are derived from other classes that are package, but not from anywhere else. You use the protected access level when it is
derived from again other classes, and so on, ultimately derived from the topmost appropriate for a class’s subclasses to have access to the method or field, but not
class that’s multilevel inheritance. for unrelated classes.
Multiple Inheritance Default (no specifier) also known as friendly
When a sub class derives from two or more super class, such an inheritance form is If you do not set access to specific level, then such a class, method, or field will be
called multiple but in Java it can not be achieved directly and is implemented accessible from inside the same package to which the class, method, or field
through Interface. belongs, but not from outside this package. This access-level is convenient if you are
Hierarchical Inheritance – creating packages.
A superclass having one or more subclasses is a case of hierarchical inheritance.
Hybrid Inheritance – #Private
A combination of two or more of the above forms of Inheritance is called Hybrid Private methods and fields can only be accessed within the same class to which the
Inheritance. 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 public final void display( )
obtained by accessor methods, but individual coordinates are not accessible to the {
user. System.out.println(“Final method in Base”);
}
public class Square public void modify( )
{ // public class {
private double x, y // private (encapsulated) instance variables pi = 3.14159265; // Illegal, as final members can not be modified
public setCorner(int x, int y) }
{ // setting values of private fields }
this.x = x; public class Derived extends Base
this.y = y; {
} public void display( ) // Illegal function, as it has been declared final in Base
public getCorner() {
{ // setting values of private fields System.out.println(“Final method in Derived”);
return Point(x, y); }
} }
}
Use of abstract keyword
So we can conclude the following about Inheritance that – // Use of public abstract class PQR // abstract class
It is the mechanism of deriving a new class from an old class {
Old class is called super class or parent class …
The new class is called sub class or daughter class }
It allows subclasses to inherit the data members and member methods of super public abstract class PQR
class {
Inheritance promotes code re-usability int a ;
Constructors of Base class are not inherited by Derived class float f ;
The this keyword can be used to refer to the most current object public void display ( ) { } // NOT an abstract method
If both sub class and super class has methods with same prototype/signature public void display1 ( ) ; // Abstract method, note the semicolon
then methods of sub class overrides the method of the super class this is called }
overriding.
The overridden super class methods can be accessed using the keyword super Use of super keyword
public class Base
The constructor of sub class can be used to invoke the constructor of super class
{
through the keyword super( ) with arguments but ensure this should be the first
public int a;
statement of the sub class constructor.
double d;
Methods declared final in the super class can not be overridden.
Base(int val1, double val2)
An Abstract class is one that simply represents the concept and whose objects
{
can not be created, it is implemented using the keyword abstract.
a = val1;
Use of final keyword and Abstract in classes and methods
b = val2;
// Using final keyword
}
public class Base
public void display( )
{
{
public final double pi = 3.14159;
System.out.println(“Display method in Base”);
} 1 0 1
} 1 1 1
public class Derived extends Base 3. ^ (equivalent to -)
{ a b RESULT
int c ; 0 0 0
Derived (int val1, double val2, int val3) 0 1 1
{ 1 0 1
super(v1, v2); // super keyword used to invoke base class //constructor 1 1 0
c = val3; 4. ~ (complementary)
}
a RESULT
public void display( )
0 1
{
1 0
System.out.println(“Display method in Derived”);
>THIS KEYWORD
}
The ‘THIS’ keyword is a reference that refers to the currently called object. The this
public static void main( )
reference is by default made available to the invoked member method.
{
>FINALIZATION OF OBJECT
Derived obj = new Derived(15, 3.1415);
@ It is a procedure that should be followed before destroying an object.
obj.display( ) ; // method of sub / derived class is invoked
@ Opposite of initialization.
super.display( ) ; // method of super / base class is invoked
@ If object contains non java resources it can’t be destroyed by using automatic
}
garbage collection.
}
>SYMBOLIC CONSTANT
>PRECEDENCE OF DATA TYPES
Variable whose value once assigned can’t be changed throughout the program .It is
DATA TYPE BITS MNEMONIC PRECEDENCE declared using ‘final’ keyword.
1 Byte 8 Bradman LOW >SINGLETON CLASS
2 Char 16 Can | A class is defined as singleton class,if only it can create one object of the class .This
3 Short 16 Score | class is useful when only one object is to be created and used in the application.
4 Int 32 Infinitely | USES:-
5 Long 64 Looking | 1. The access of the object is controlled.
6 Float 32 For V 2. When “just in time “instantiation is needed and needed globally.
7 Double 64 Double HIGH
>WHAT IF ‘public’ IN ‘public static void main(String ar[])’ IS CHANGED TO
>BITWISE OPERATORS ‘private’?
1. & (equivalent to *) if ‘public’ is changed to ‘private’ ,it will compile without any error but runtime error
a b RESULT will occur
0 0 0 “main method not public”.
0 1 0 >OPERATOR ASSOCIATIVITY
1 0 0 Operator associativity is the grouping of operands and operators in an expression
1 1 1 where more than one operator of the same precedence is used
2. | (equivalent to +)
a b RESULT
0 0 0 UTKARSH DAYAL
0 1 1