You are on page 1of 7

Java Notes for Class X

OBJECT An object is an identifiable entity with some Keywords are the words that convey a special meaning to
characteristics & behavior. the language compiler (if , for etc.)
Eg. 1 Orange 2 chair Identifiers are the name given to different parts of
characteristics program e.g. variables ,objects, class, arrays, function.
1. It is spherical shape and color is orange Literals are constant i.e. data item that are fixed values
2. It has four legs, back and arms i.e. integer, Boolean, character, null, floating, string.
behavior Punctuators separators e.g. () , [], {}
1. It is citrus in nature and taste sour. Operators = ,>, <, = =, : etc.
2. It lets you sit on it Data types are means to identify that type of data and
Object interact with each other by passing message. associated operation of handling it.
Basic concept of OOP(object oriented programming) 1) primitive (byte, short, int, long, float, double,
1.Abstraction refers to the act of representing essential char, boolean)
features without including the background details or 2) Reference(class, array, interface).
expressions.
2.Encapsulation the wrapping of data and functions into
a single unit (class) is known as encapsulation. Type Size Range Initial
3.Inheritance is the capability of one class of things to 0
Bits Byte Lowest Highest
inherit capabilities and properties from another class.
4.Polymorphism is the ability for a message or data to be byte 8 1 -128 127 0
processed in more than one form.(function/constructor short 16 2 -32768 32767 0
31
overloading). int 32 4 -2 231 -1 0
The object is implemented in software term as follows. long 64 8 -263 263 -1 0
1. characteristics & Attributes are implemented float 32 4 -3.4E+38 3.4E+38 0.0f
through member variables or data items of the objects
2. behaviour is implemented through member function
double 64 8 -1.7E+308 1.7E+308 0.0d
called char 16 2 0 65536 null
methods/function. boolean 8 but uses true false false
Class represents a set of objects that share common 1 bit
characteristics & behaviour. all reference type null
A class is an object maker or object factory. Created
objects are knows as instance of class.
Source program the program written in high level Reference in java is a data element whose value is an
language by programmer is called source code. address.
Machine code Computer needs source code to be Scope generally refers to the program region with in
converted into low level language to be executed which a variable/method is accessible. The broad rule is
Byte code in java source code is not converted into a variable accessible with in the set of braces it is
machine code but is converted in byte code while declared.
compilation which is same for all machines Final keyword final while declaring a variable makes it
Compiler/Interpreter They both are used for translating constant i.e unchanged
HLL into machine language. Compiler does it at once Operators operations are represented by operators and
while interpreter does it line by line. objects(values) of the operation are referred as operands.
JVM Java Virtual Machine is a java interpreter which Unary +, -, ++, —. Binary +, - *, /, % Ternary ?
translates byte code for specific platforms. Relational >, <, ==, >=, <=
Characteristics of java. Logical AND, OR, NOT Bitwise &, |, !, <<, >>
1.Write once run anywhere 2.light weight code 3 Prefix follow first change then use(e.g. ++c)
security 4 .built in graphics 5. object oriented language Postfix follow first use then change(e.g. c++)
6.supports multimedia 7.platform independent 8.open Shortcuts
product 1. c=c+1  c+=1 2. c=c*4  c*=4
Java Character set character set is a set valid characters 3. x=x-10 x-=10 4. x=x/2 x/=2
that a language can recognize(i.e letters, digit,sign etc) Expression in java is any valid combination of operators,
Unicode java uses Unicode character set. Unicode is a 2 constants and variables. It can be pure or mixed. In pure
byte character code set which represents almost all all the operands are of same data type in mixed they are
characters first 128 are identical two ASCII code. of mixed data type.
You refer to a particular Unicode by using \u followed Type conversion the process of converting one
by 4 digit hexadecimal number predefined type into another is called type conversion.
Tokens the smallest individual unit in a java program is Implicit(coercion) type conversion is performed by java
known as token. which are keywords, identifiers, literals, compiler where smaller data type are promoted into
punctuators, operators. higher data types.
Explicit type conversion is performed by the user using // set of instructions to be performed when function is
type operator. called.
Block is a group of zero or more statements between }
balanced braces also known as compound statement. The first line of function is known as function prototype.
To declare variable that are members of a class the Access specifier is used to set the accessibility of the
declaration must be within the class body. function i.e. to set whether the function can be
Class variable(static) a data member that is declared accessible outside that class or not. It can be public or
once for a class. All objects of the class type share these private or protected or no access specifier can be given
data members as there is single copy them available in then it is treated as friendly which is not a key word.
memory. Modifier :- static is used as modifier if function is not
Instance variable a data member that is created for every declared as of static type then we can call that function
object of the class if there are ten objects of a class type with the help of object of that class type with in which it
there would be 10 copies of instance variable one each is declared and we can also use instance variables( global
for an object. variables ) inside that function. But if function is
new is used to create an object of a class and associate declared as of static type then we can call that function
the object with a variable that names it. with the help of its class name NOT with the help of
Dynamic Initialization:- When a variable is initialized objects and we CANNOT use instance variables( global
through a valid expression than it is known as dynamic variables ) inside that function. We can use only those
initialization e.g int c= a*b*c+4*5; global variables which are declared as of static type.
rvalue(realvalue) and lvalue(location value) GLOBAL VARIABLES : are the variables which are
rvalue :- the value stored in variable declared inside the body of class.
lvalue :- the memory address where the value is stored RETURN TYPE state that after processing function is
eg int a=5; going to return which type of value. It can be any valid
in the example 5 is the rvalue where as memory address java data type(i.e. primitive or reference). A function at a
of a will be lvalue time can return only one value. If function is not going
label :labels are typically used on blocks and loops. to return any value then return type should be of void
Labeled blocks are useful with break and continue eg: type. For returning the values to the place from where
label name : statements the function is called return statement is used. return
Type Promotion conversions of all operands upto the statement also causes the immediate exit from the called
type of the largest operand( implicit type conversion) function.
Escape sequence or non graphic characters are those Signature refers to the number and type of arguments
characters which can’t be typed from keyboard. Which is mentioned in function prototype.
represented by \ followed by one or more characters Actual parameters are the parameters appearing in
Operator precedence :- determines the order in which function call statement.
expression are evaluated. Formal parameters are the parameters appearing in
Operator associatively : Associatively rules determine function prototype.
the grouping of operands and operators in an expression We have to always keep in mind that the number, type
with more than one operator of the same precedence. and sequence of actual parameters should be equal to
FUNCTIONS the formal parameters.
Functions or methods are the set of instructions to Function calling in java all functions can be called in
perform a particular task or process. They are also two ways.
known as sub program or subroutine or member Call by value or call by reference
methods. They represents the behavior of objects. when we are passing primitive type of values then it is
Why Functions call by value. In this the duplicate copy of original
1.Reduces complexity of the program. values are passed.
2.Makes the reuse of process or task possible. when we are passing reference types(array, objects)then
3. helps in data hiding. it is call by reference. In this instead of passing values
In java functions are basically of two types the memory address(reference) of values is passed.
inbuilt functions and user defined functions. During call by value any change in the formal
inbuilt functions i.e. the functions which are by default parameters is not reflected back to actual parameters but
present with java language. in call by reference changes in formal parameter are
user defined functions i.e the function defined by user reflected back to actual parameters.
according to his need. Pure function are those that do not change the state of
// further we discuss user defined functions their parameters.
Syntax for declaring the function. public static boolean after (Time time1,double secs)
Access_Specifier Modifier Return _Type Function {
Name ( Arguments) if(time1.hour>time2.hour)
{ return true;
//definition of the function }
// or
Impure function(modifier) are those that change/modify Example
the state of their parameters are also known as mutator class cons
function. {
public static void after (Time time1,double secs) int a,b; // data members of instance type
{ char ch; // data members of instance type
time.second +=secs; public cons() // non parameterized constructor
if(time.second>=60.0) { // name of class and constructor are same
{ a=0;// constructor does not have any return type
time.second-=60.0; b=0; //not even void type
time.minute+=1; ch=’ ‘;
} }
} }
Function overloading if there are more then one Non Parameterized constructor(default) if a class has
function or method by same name (in the same scope) no defined constructor the compiler will supply a default
that are differentiated by their signature is called an constructor it initializes the data members by any
overloaded function. This process is called function dummy value.
overloading(it implements polymorphism). Parameterized constructor a constructor receiving
Example arguments is known as parameterized constructor. It
// aprogram to find area of circle, square ,rectangle. allow us to initialize the various data elements of
import java.io.*; different objects with different values when they are
class overloading created. It also hides the default constructor.
{ class cons
public static void main( String args[])throws Exception {
{ int a,b; // data members of instance type
BufferedReader d = new BufferedReader(new char ch; // data members of instance type
InputStreamReader(System.in)); cons(int a1,int b1,char c) //parameterized constructor
System.out.println(“enter side of square”); { // name of class and constructor are same
int side=Integer.parseInt(d.readLine()); a=a1;// constructor does not have any return type
System.out.println(“enter length of rectangle”); b=b1;//not even void type
int len=Integer.parseInt(d.readLine()); ch=c;
System.out.println(“enter breadth of rectangle”); }
int br=Integer.parseInt(d.readLine()); }
System.out.println(“enter radius of circle”); Constructor overloading is also possible.
double r=Double.parseDouble(d.readLine()); Differences between method and constructors are as
area(side); // function calling follows
area( len , br); // function calling 1. method has return types but constructor doesn’t have
area( r ); // function calling any return type.
}// end of main 2. constructors have the same name as class has but
public static void area(int t) //function prototype methods can have different names
{ 3. methods are called using class name and objects of
int area = t*t; that class but constructors are invoked automatically
System.out.println(“area of a square = “+area); at time of creation of object of that class type.
}// end of function area Using Library Classes
public static void area(int l, int b) //function prototype Input/Output Streams
{ Input(means reading)(ex. keyboard, mouse, file, audio)
int area = l*b; Output(means writing)(ex. screen, printer, speaker)
System.out.println(“area of a rectangle = “+area); System.in(the input stream)is connected to keyboard
}// end of function area stores information about connection between input
public static void area(double ra) //function device and computer or program.
prototype System.out & System.err(the output stream) is connected
{ to monitor.
double area = 3.14 *ra * ra; Byte oriented we can read data of any type data type
System.out.println(“area of a circle = “+area); with them as bytes are read. These streams are known as
}// end of function area data streams (e.g. DataInputStream and
}// end of class overloading DataOutputStream)
CONSTRUCTOR Character oriented only characters are read through
A member function with the same name as its class is these types of streams. The streams are known as Reader
called constructor and it is used initialize the data and Writer Streams.(e.g. InputStreamReader and
members of that class with legal initial value. BufferedReader but these streams are exclusive oriented
Data members are those variables which are declared to Unicode)
inside the body of class.
InputStreamReader translates data bytes received from stored in dictionary). equals return boolean type of value
InputStream objects into stream of character. where as compareTo returns integer type of value.
BufferedReader buffer(stores) the input received from  length();
an InputStreamReader . Syntax- int length();
Exception handling Usage- This function returns the length of
Exception: is an unexpected situation or in short an characters present in the string.
error that is unexpected.  charAt();
Exception handling is a transparent and nice way to Syntax- char charAt(int n);
handle program errors. Usage-This function returns nth character of the
1.Compile(syntax)time errors : Syntax errors or errors string.
found while compiling a program.  toUpperCase();
2.Run time error the errors that occur during runtime Syntax- String toUpperCase();
because of unexpected situations. Such errors are Usage- This function/method is to convert all the
handled through exception handling routines. character of the string into uppercase.
eg. Of run time errors :- divide zero , index out of  toLowerCase();
bounds Syntax- String toLowerCase();
3.Logical errors. Errors in the logic can be found by Usage- This function/method is to convert all the
viewing the output manually. characters of the string into lowercase.
4. Way of handling anomalous (unexpected) situations in  replace();
a program run is known as exception Handling. Syntax- String replace(char ch1,char ch2);
There are five keywords which are used to handle ch1- character to be replaced.
exceptions in java i.e.try, catch, throw, throws, finally. ch2- character by which to be replaced.
throw keyword forces an exception. Usage- This function replaces all the occurrances of
the character ch1 with ch2 in the string.
throws it will automatically report it to error handler
 trim();
or processor.
Syntax- String trim();
try is for enclosing the code where in exceptions can Usage- This function is used to remove all the white
take place. spaces at the beginning and end of the string .
catch traps the exception and handles it.  equals();
finally keyword can be used to provide a block of Syntax- boolean equals(String2);
code that is always performed regardless of whether Example-s1.equals(s2);
an exception is signaled or not. Usage- This function gives true if s1 equals to s2.
try  concat():
{ Syntax- String concat(String2);
} Example-s1.concat(String s2);
catch(exceptionname e1) Usage- This function concatenates s1 equal to s2 .
{  substring();
System.out.println(e1.getsMessage()+”———”); Syntax- String substring(int n);
} Usage-This function returns substring starting from
finally the nth character of the string.
{  substring();[another format]
} Syntax- String substring(m,n);
A catch block can accept one exception only. For Usage-This function returns substring starting from
multiple exception multiple catch blocks are to be Mth character upto the nth character without
written. including the nth character.
5. a. Difference between throw and throws is that a.  indexOf();
throw cannot be given with function prototype but Syntax for string- int indexof(String str);
throws can be. Syntax for character- int indexOf(char ch);
b. using throw it is possible for your program to throw Usage-This returns the position of the first
an exception explicitly but throws clause lists the occurrence of the character or string in the string.
types of exception that a method may throw.  indexOf()(another format)
STRING Syntax- int indexOf(String str, int start index)
String – String is a series of character which includes  int indexOf(char ch , int start index)
spaces also. String is a class not a data type. Example- int indexOf(“the”,n);
The string object are immutable (unchangeable) but  int indexOf(‘y’,n);
string buffer are mutable. This format gives the position of “the” and ‘y’
STRING FUNCTIONS / METHODS OF JAVA starting from the nth position in String.
equals and compareTo :- equals and compareTo they  compareTo();
both are used for comparing the strings equals compare Syntax- int compareTo(string str);
only for equality where as compareTo compares the  Example-s.compareTo(s1);
string lexicographically(i.e the way in which words are
Usage-This function returns negative if s is less than The default(friendly or package) members are accessible
s1,positive if s is greater than s1 and zero if s is equal inside their class as well to the classes in the same
to s1. This compares two string lexicographically. package.
 boolean endsWith(String str) The default access specifier is friendly which is not a
Usage- Tests if the this string (current String keyword.
object)ends with the specified suffix (str). An abstract class is the one whose objects cannot be
 int lastIndexOf(char ch) created however other class can inherit from it.
Usage-returns the index within the this string of the dot (.) the dot(.) accesses instance member of an object
last occurrence of the specified character. or class members of a class.
 stringreplace(string s1, string s2) DECISION MAKING STATEMENTS
Usage-It replace string s1 with string s2. 1. Sequential construct :- generally the program is
PACKAGES executed sequentially i.e. line by line from top to bottom
A package is a group of logically related classes 2. Selection construct :- means the user wants to
To help programmers be more productive java includes execute a statement or statements based a particular
predefined classes in the form of packages as the part of condition. If true then a particular statement(s) and if
installations these are called java class libraries. false then a other set of statement(s). For doing so in java
if-else and switch statements are used.
1. java.lang(language) is automatically imported by 3. Iteration construct :- means the user wants to repeat
runtime system a set of statement(s) or process again and again
2. java.util(utilities)e.g. date, calendar depending upon a particular condition. In java for
3. java.io(input/output) forming iteration construct for , while and do- while
4. java.awt(graphics) statements are used.
5. java.applets(applets)
if-else statement :- the if – else statement tests an
6. java.net(network services)
expression and returns boolean type of value i.e. true or
package statement in a program creates a package and
false
makes all following classes its part.
if true then the statement(s) given after if statement are
packages and their classes are imported(accessed)
executed and if false statement(s) given after else
through import statement in the program.
statement are executed.
Wrapper class
Syntax: if(condition)
Number of primitive data type = Number of wrapper
{
class but starts with upper case character .(eg. Byte,
// statement(s) to be executed if condition is true
Short, Integer, Long, Float, Double, Boolean, Character)
}
Uses :
else
1- Converting from character strings to numbers
{
and then to other primitive data type.
// statement(s) to be executed if condition is false
2- A way to store primitive in an object.Wrapper
}
class
More information about class  ? : (ternary operator):- it can be used instead of
Composite data type if – else statement
The data type that are based on fundamentals or Syntax
primitive data types are known as composite data types. (condition)?statement(s):statement(s)
Since these data types are created by users, these are also example
known as user defined data types. if(a>b) using ternary operator
Class is also composite type. c=a; c=(a>b)?a:b;
A class containing main() method can not be termed as else // if condition is true then statement after ?
user defined data type it is termed as application. c=b; will be executed if false statement given
To create a object. after : (colon)sign will be executed
Point point1 = new point() switch statement : it is a multiple-branch selection
statement. This selection statement successively tests the
Classname objectname newoperator constructor
value of a variable against a list integer or character
Point point1 constants.
Declaration do not create objects they are created using Syntax :
new operator. switch(variable) // value of variable is to matched with
The dot operator is used to refer to members of an { //constant given with case statement and
object(e.g. object reference.membername)
when match is found statements given case
Access specifiers constant :statement(s) // after that case are
public members are accessible everywhere in the break // executed, then control
program. case constant : statement(s) // is transferred outside
private members are accessible only inside their own break; // switch block using
class.
case constant : statement(s) // break statement. If no
protected members are accessible inside their own class, break; //match is found then the
sub class and package. default :statement(s); //control will be
//transferred to the }
//statement(s) given More then one initialization and updation can be done in
//after default statement one for statement separated by comma (,) sign.
} Example :
if the control flows to the next case below the matching for(i=0,s=0;i<10;i++,s++)
case in the absence of break is known as FALL 2. while and do-while loop : are used when number
THROUGH of iterations are unknown.
Values given with each case should be unique i.e. no Syntax
matching values can be given with case a. initialization b. initialization
 dangling else :- when the number of ifs are more while(test condition) do
then the number of else then it is known as dangling else. { {
Example :- loop body loop body
if(a>b) // in this example there is a updation updation
if(a>c) //confusion that given } }while(test condition);
System.out.println(a); // else is related with which if Some examples of loop variations
else a. Infinite loop : the loop which never ends is known as
System.out.println(b); infinite loop.
To over come this problem {} curly braces are used. Example
if(a>b) 1. for(;;)//steps are not given
{ { loop body
if(a>c) System.out.println(a); }
} 2. for(int i=0;;i++)//test condition is not given
else { loop body
System.out.println(b); }
 differences between if-else and switch case is 3. for(int i=0;i<10;)//updation not given
{ loop body
a. using if else we can compare more then one values
}
but using switch case we can test only for one
4. int i=0; 5. while(true)
value.
while(i<10) {
b. using switch case we can test only for equality but
{ loop body
using if else we can test for >, <, or equality.
loop body }
c. in switch case only integer and char type values are
}
used. But in if else all data type values can be used.
time delay loop :- if a loop does not contain any
d. A switch statement is usually more efficient than a
statement in the loop body it is said to be empty loop
set of nested ifs. both if and switch can be used in
they are used as time delay loop in the program
nested forms.
examples ;
ITERATION THROUGH LOOPS
1. for(i=0;i<10000;i++) 2. int i=0;
Loops are used for repeating a statement or set of
{ while(i<10000)
statements or a process again and again. For forming a
} {
loops three steps are
or i++;
1. Initialization
for(i=0;i<10000;i++); }
2. Test Condition
3. Updation(increment or decrement)
Jump Statements :-these statements are used for
In java for formaing loops three statements are used they
transferring the control of program from one part of the
are
program to another part of the program. The jump
1. for loop 2. while loop 3. do-while loop
statements used in JAVA are 1. break 2. continue 3
1. for loop : generally for statement is used when the
return .
number of iterations are known or fixed.
Where as a library function System.exit() is used to
Syntax
jump out from program
for(initialization; test condition; updation)
1. break statement is used with blocks(eg. switch case)
{
or loops to jump out from loop or block to the statement
//loop body
given just after that block or loop.
}
Example :
in the syntax of for statement all the three steps are
for(i=0;i<10;i++)
optional but semicolon signs are must.
{
example.
if(i==5)
1. for(;;)// Example of infinite loop
break;
2. int i=0
System.out.print(i);
for(;i<10;)
}
3. for(i=0;i<10;)
statement 1.
{
i++;
2. where as continue statement is used to transfer the 5. Array advantages and disadvantages
control to the next iteration Advantages :-
Example :- a. easy to specify :- declaration, allocation and
for(i=0;i<10;i++) initialization can be done in one line.
{ b. free from run time overheads memory allocation one
if(i==5) time
continue; c. random access of elements.
System.out.print(i); d. free sequential access it is faster.
} Disadvantages
3. return statement is used to return a value from the a. need to know size
function to the function from where that is called or you b. careful design required.
can say return statement is used to make the immediate 6. Aliasing :- In call by reference when we pass the
exit from the function within which it is used. reference (address) into another variable then another
4. Nested Loops : when there are loops inside loop then name is given to the same memory location that is
they are said to be nested loop. known as aliasing.
Differences and similarities in loop statements:- 7. new keyword :- the new operator is used o create an
1. for, do – while and while they all are used for object of a class and associate the object with a variable
forming that names it. It can be used to create a new object or
loops. new array.
2. They both are entry control loops where as do – while 8. Difference between reference and primitive type:-
is In reference type all the operations are based on address
a exit control loop. where as in primitive type all the operations are based on
3. In while loop if the test condition is false it will not values. Reference type are user defined and are formed
be using primitive type where as primitive type are inbuilt
executed at least once but in do while even if the type
condition is false it will be executed at least once.
ARRAY
An array is a collection of variables of the same type that
are referenced by a common name.
1. Types:- one dimensional, two dimensional.
2. Declaration
An array is declared by specifying its base type, name
and size.
int a[]=new int[10]; or int []a = new int[10];// single
dimension
int a[][] = new int[4][4] or
int [][]a= new int[4][4] // double dimension
Total bytes in single dimension = size of type * size of
arrayTotal bytes in double dimension =no.of rows*no.of
columns*size of base type.
3. Searching
In linear search each element of the array is compared
with the given item to be searched for one by one.
Binary search searches for the given item in sorted
array. The search segment reduces to half at every
successive stage. Binary search can work only on sorted
array and takes less time in searching by dividing the
array in two parts where as linear searching works on
sorted as well as unsorted array and takes more time.
4. Sorting
Sorting of an array means arranging the array elements
in a specified order.
In selection sort the smallest(or largest depending on the
desired order) key from the remaining unsorted array is
searched for and put in the sorted array. This process
repeats until the entire array is sorted.
In bubble sort the adjoining values are compared and
exchanged if they are not in proper order. This process is
repeated until the entire array is sorted.

You might also like