Sie sind auf Seite 1von 19

JAVA THEORY Examples of OOP based languages are Simula, C++, Java, Python, and Smalltalk etc…

>What is Java? Basic Principles of OOP


Java is a 3rd Generation Object Oriented programming Language, developed by 1) Encapsulation – Binding up of data members and member functions together
James Gosling in the year 1995. It was initially codenamed as Green and into a single unit called (class) is called Encapsulation.
hypothetically called Oak named after the Oak tree outside Gosling’s house. 2) Data Abstraction – Act of representing only essential features without including
It is case sensitive and has a unique two step translation process that includes both its background details is called Data Abstraction.
Compilation and Interpretation which makes Java Platform independent. 3) Polymorphism – The ability of a method to behave in more than one form is
called polymorphism. Function Overloading is a way to implement it, in which more
>What is Procedure Oriented Programming Language? than one function has the same name but different argument list.
Pop is a Procedural Oriented Programming Language. In this, the stress is laid on 4) Inheritance – The ability of a class to derive the properties from another class is
function rather than data. Data may be kept floating throughout the Programming. called Inheritance. The class that inherits is called the Derived / Sub / Daughter class
Hence by scanning the whole program from beginning to the end and we can rectify and the class from which it is derived is called Base / Super / Parent class. The
any error caused. E.g. of POP based language are GW-BASIC, C, etc… keyword used to implement Inheritance is ‘extends’.
Characteristics of POP 5) Object – It is an identifiable entity with some characteristics and behaviour.
1) Emphasis is laid on functions (Logical steps). 6) Class – It is a blueprint that represents a set of objects which share common
2) Functions share global data. characteristics and behaviour.
3) Data values can keep floating from one function to another. Related Terms :
4) Uses top down approach of programming. Data binding – is the process to link to the function call with function signature at
Drawbacks of POP run-time i.e., during execution of a program.
1) As Data values are global to all the functions, you may require making necessary Attribute:-The characteristics which make every object having its identity make
changes in the functions due to change in the data values. them distinguished is called attribute.
2) It is not suitable to solve complex problems in real situations. Behavior – The behavior 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
>What is Object Oriented Programming Language?
passing information to and from one another, this is called Message Passing
OOP is an Object Oriented Programming Language. It is a modular approach to
Data Hiding – is the data which cannot be accessed directly outside, class premises
programming in which equal stress is given to data as well as methods and it allows
although they are available in the same program
the data be applied within the stipulated program area. It also provides reusability
Garbage Collection – The Garbage-collected Heap is where the objects in Java
features to develop productivity logic.
programs are stored. Whenever we allocate an object using new operator, the heap
Features of OOP
comes into picture and memory is allocated from there. Java does this
1. It gives equal stress on data and function.
automatically using Garbage collection mechanism, using an algorithm named Mark
2. It makes the program simple by dividing it into a number of objects.
& Sweep logic. Remember that the local object reference resides on Stack but the
3. The objects can be used as a bridge to have data flow from one function to
actual object resides in Heap only. Also, arrays in Java are objects, hence they also
another.
resides in Garbage-collected Heap.
4. Data can be easily modified without any change in the function.
Different Types of Java Programs
Advantages of OOP
1) Standalone Application – An application program that is developed by
1) we can extend the use of existing class through inheritance.
programmers which consists of various methods and these methods being invoked
2) Using the concept data hiding can generate secured program.
from within a ‘main ( )’ method is called standalone application.
3) We can create different modules in our project through objects.
2) Internet Applets – These are small java programs that are embedded in a web
4) Multiple instances of an object can be generated to co-exist without any
page and which requires a web browser to be run/executed.
interference.
3) Servlets – They extend the functionality of web browser.
5) It is highly beneficial to solve complex problems.
Source Code – The High level language code written by programmers which is not
6) It is easy to modified and maintain software complexity.
understandable by the computer is known as Source Code. It has an extension of
*.java 4. Operators
Byte Code – is an intermediate code that consists of a set of pseudo machine 5. Separators
language instructions that are understood by the JVM and are independent of the Hint: Try to remember KILOS
underlying hardware. It is called byte code because each chunk of code is of 8 BITS  Keywords are the reserved words which convey a special meaning to a
(1 byte = 8 Bits). language compiler. They can not be used for any other purpose like function
The byte code files have an extension of *.class name, variable name or object names.
Object Code – The interpreter of Java named JVM (which stands for Java Virtual There are around 48 keywords, of which const and goto have been reserved
Machine) then converts the intermediate Byte Code into machine specific even though they are not currently being used for any purpose true, false and
executable which runs on the host machine. null might appear to be keywords but actually they are literals, and hence are
API (Application Programming Interface) – consists of libraries of pre compiled reserved words.
code that programmers can use in their application and programs for designing  Identifiers are fundamental building blocks of a program. They are named
softwares. Hence we can say that Java API consists of functions and variables that memory locations or simply names given to variables, objects, classes,
programmers can reuse. functions, arrays etc… They are case sensitive.
Java Packages – Packages are collection of similar nature classes. A package can be There are certain Identifier naming rules –
created by using the keyword ‘package’ and the keyword used to include a package 1. They can consist of infinite number of alphabets and digits
in our program is ‘import’. Java contains an extensive library of pre-written classes 2. They must start with an alphabet and not with a digit
grouped together into packages – 3. They can not be a keyword or reserved word
# java.lang.* It is a default package containing String, Math, Integer, thread etc. 4. They cannot have any spaces
# java.io.* It is the basic Input Output package of Java 5. They cannot contain any special character other than _(underscore),
# java.util.* The java utility package $(dollar)
#java.applet.* The applet package While naming identifiers there are certain conventions that make them
#java.net.* The Networking package of Java identifiable
# java.awt.* It stands for Abstract Windows Toolkit, for designing Windows based 1. Class names begins with an Uppercase character
applications. 2. Identifiers having multiple words, the first character of 2nd and subsequent
Basic Features of Java:- words are in Uppercase
1) Write once run anywhere(WORA) 3. Constants are in all CAPITALS
2) Platform Independent Comments (Remarks):- refers to statements which are ignored by the java compiler
3) Offers many security features to make its program safe and secure and increase the readability of a program. These are used to state a purpose of the
4) Built in graphics & supports multimedia instructions used in a program.
5) Light Weight code  Literal are the fixed values that are assigned to variables which do not change
6) Open Product… i.e., freely available to all. its values during program execution. They are of 5 types –
Blue – J 1. Integer Literal
>Java Tokens & Character Set i. Decimal
It is a set of valid characters that a language can recognize. The character set of Java ii. Octal
is UNICODE. This has been selected due its vastness of characters. It is 2 byte iii. Hexadecimal
character code. The first 128 characters of Unicode are identical to the ASCII To represent Decimal Integers we simply use the integer type number as literal, e.g.
character set. int p = 45; So, System.out.println(p); // Shows 45 as output
Tokens are smallest individual units of a Java program. There are 5 different types To represent Octal Integers however we precede the number with a 0 (zero) as
of tokens in Java – literal, e.g. int p = 045;System.out.println (p); // Shows 37 as output coz, (45) in
1. Keywords octal is 37 in decimal number system.
2. Identifiers Moreover to represent any Hexadecimal Integer we use 0x (Zero and lowercase
3. Literals 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 >Type conversion The process of convert one primitive datatype to another either
decimal number system. from lower precision to higher or vice versa I known as type conversion. This can be
2. Real Literals achieved in two ways –
i. Floating point literals have 7 digits of precision after the decimal point Implicit Data Type Conversion – Such Type of conversion is performed by the
ii. Double literals have 16 digits of precision after decimal point compiler without programmer’s intervention. In this type of conversion a datatype
3. Character Literals are enclosed within a pair of single quotes of lower precision gets converted to a datatype with higher precision.
char ch = ‘A’; e.g. int a = 10;
Character type user inputs are taken in the following way – double d = a;
e.g. char ch = (char) in.read ( ) ; System.out.println(d);
4. Boolean Literal The above code snippet gives 10.0 as output; this clearly indicates that the int
There are only 2 types of boolean literals i.e. true & false the default being false. datatype got automatically converted to double.
5. Null Literal Explicit data type Conversion – Such type of conversion is user defined conversion
 Operator – are the entities or symbols that tell the compiler that what which forces an expression to be converted into specific type. Generally this is done
operation has to be performed with one, two or three number of operands to force a conversion from higher precision data type to lower.
within a given expression. e.g. double pi = 3.1415;
There are approximately a set of 37 different operators that Java uses int i = pi;
Operators can either operate on 1, 2 or 3 operands and accordingly named as – The above statement is considered illegal and hence gives an ERROR message
Unary (works on 1 operand) e.g. + + and – – “POSSIBLE LOSS OF PRECISION”
Binary (works on 2 operands) e.g. +, – , * , / , >, , = , > , << ) Hence the above code should be Type Casted in the following manner –
Special Operators (this , dot (.) , new, (type) , instanceof ) int i = (int) pi;
System.out.println(i);
>Data types Now, the output to the above code will be 3
They are the entities that tell the compiler that which variable will hold what kind of Potential problems with Type Casting
values. 1. When a datatype is converted from double to float results in loss of precision i.e.
Primitive data types – Also called as Basic Data type. They are pre defined or built a double datatype has 16 digits after decimal point which gets truncated to 7 digits.
in data types because they are already built in java. E.g. byte, short, int, long, float, 2. When a datatype is converted from double or float to integer type results in loss
double, char, boolean. of entire fractional part leaving behind only the integral part.
Non Primitive Data Types: Directly or indirectly dependent on primitive data types. 3. When a higher order integer datatype like int or long is converted to byte or
They store the data values with reference to the address or locations. So, they are short might result in the data going out of range.
called as Reference Data Types. E.g. array, classes interfaces etc… Take an example
Range, Size and hierarchy of various primitive data types int a = 130;
Type ….Size…. Range byte b = (byte) a;
boolean 1 bits 1 byte true and false System.out.println(b);
byte 8 bits 1 bytes 128 to + 127 The output for the above code is – 126
char 16 bits 2 bytes 0 to 65,535 Explanation for the above –
short 16 bits 2 bytes -32768 to +32767 The above code tries to type cast int to byte, the data range for int is – 2 31 to + 231
int 32 bits 4bytes -2E31 to + 2E31 – 1 – 1 whereas that of byte is – 128 to + 127, hence think in terms of a Number Line,
long 64 bits 8bytes -2E63 to + 2E63 – 1 when we start filling 130 in the number line starting from 0 (zero) we reach the end
float 32 bits 4bytes -3.4E+38 to +3.4E+38 of the line at 127 and so the filling process continues from the –ve end and finally
double 64 bits 8bytes -1.7E+308 to 1.7E+308 reaches – 126, hence the output…
>Operators in Java 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 #Relational Operators are used to find the relationship between two quantities,
Operators can either operate on 1, 2 or 3 operands and accordingly named as – whether they are equal, un-equal, greater than less than etc…
Unary (works on 1 operand) e.g. + + and – – SYMBOL RELATIONSHIP
Binary (works on 2 operands) e.g. +, – , * , / , >, <, == etc…
> Greater than
Ternary (works on 3 operands) e.g. ? :
Operators can categorized as – < Less than
#Arithmetic Operators +,–,*,/,% >= Greater than or equal to
#Relational Operators > , < , >= , <= , == , !=
<= Less than or equal to
#Logical Operators &&, || , !
#Conditional Operators ?: == Equal to
#Bitwise Operators &, | , ~ , ^ != Not equal to
#Shift Operators >> , <<
#Logical Operators are used to join 2 or more relational operators and of 3 types –
#Special Operators this , dot (.) , new, (type) , instanceOf
&& (and) returns true when both or all the relations are true
#Shortcut Operations in Java
|| (or) returns true when any one of the relations are true
Java implements shortcut methods to work with basic arithmetic operators like
! (not) inverts true to false and false to true
+, – , * , / and %
Say if the value of a=4, b=6 then…
Hence, a = a + 5; can be written as a + = 5;
if(a>5 && b>5) will return false coz both the conditions are not true
And the above + = operator is called Addition Assignment operator.
if(a>5 || b>5) will return true coz one of the conditions is true
Similarly we have –
if(!true) will return false
Subtraction Assignment a– =5
It is not mandatory to have a relation always inside an ‘if’, even without any ‘if’
Multiplication Assignment a*=5
clause we can check the return of any relation like –
Division Assignment a/=5
Say the value of x=7; then
Modulus Assignment a%=5
System.out.println(x==7); will give the output as true, and if we place (!) in front of
Unary Operators
the relation, System.out.println( ! (x==7)); will invert the output from true to false.
Post/Pre – Increment and Post/Pre – Decrement Operators
# Bitwise and Shift Operators
a = a + 1 can also be written as either a++ (Post Increment) or ++a (Pre Increment)
Operator Name Description Example Result
a = a – 1 can also be written as either a– – (Post Decrement) or – –a (Pre
1 if both bits are 1 and 0 in all other
Decrement) a&b and 3&5 1
cases
The difference between Pre and Post is –
0 if both the bits are 0, rest all other
In a Postfix operator like Post Increment or Post Decrement the value of the a|b or 3|5 7
cases 1
operand is first used and then increased or decreased as the case may be for e.g.
int a = 5; 1 if two bits are different and 0 in all
a^b xor 3^5 6
System.out.println(a++); other cases
Gives 5 as output as the value of ‘a’ is first used and then increased to 6, so if we Inverts the bits, after transforming the
have one more print statement after the above stated line will give 6 as output. ~a not entire number into full bit ~3 -4
System.out.println(a); // Output is 6 representation
In a Prefix operator like Pre Increment or Pre Decrement the value of the operand is Shifts the bits of n towards left by p
first increased or decreased as the case may be and then used for e.g. n << p left shift positions thereby adding Zeros to the 3 << 2 12
int a = 5; extreme LHS
System.out.println(++a); Shifts the bits of n towards right by p
right
Gives 6 as output as the value of ‘a’ is first incremented and then displayed. n >> p positions resulting in loss of bits from 5 >> 2 1
shift
LHS
In all the above examples the operands (values) must be converted to Binary and >Math class functions
then implemented with respective operators except for Right and Left Shift They are in Java (default package of Java named java.lang)
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 Function Name Description
uncommon bitwise and. Although the bitwise andcan also be used with boolean 1 Math.sin(r) Returns sine of angle ‘r’ given in radians
operands, this is extremely rare and is almost always a programming error. 2 Math.cos(r) Returns cosine of angle ‘r’ given in radians
# Conditional Operator 3 Math.tan(r) Returns tangent of angle ‘r’ given in radians
The only Ternary operator of Java is the Conditional Operator, ? : which can be used 4 Math.asin(x) Returns the angle in radians whose sine value is ‘x’
as an alternative to if…else
5 Math.acos(x) Returns the angle in radians whose cosine value is ‘x’
Syntax: variable = condition ? true : false ;
6 Returns the angle in radians whose tangent value is
e.g. int n = 100>50 ? 1 : 0; Math.atan(x)
‘x’
In the above code the value of ‘n’ becomes 1 as the condition 100>50 is true, had it
7 Math.toDegrees(r) Converts Radians to Degrees
been wrong the value of ‘n’ would have been 0;
8 Math.toRadians(d) Converts Degrees to Radians
Special Operators
# [ ] this operator is used to assign the size for an array and to access any 9 Math.min(a, b) Returns the smaller among a and b
particular element within an array. 10 Math.max(a, b) Returns the larger among a and b
# ( ) the parenthesis operator is used to enclose the arguments to a function in 11 Math.abs(a) Convert -ve magnitude to +ve magnitude.
the function prototype line and invoke a function by enclosing the list of arguments. 12 Math.sqrt(x) Returns the square root of ‘x’
# Dot (.) the dot operator is used to access the instance/class members of a class 13 Math.pow(x, y) Returns x to the power of y
through an object or class name. 14 Returns ‘e’ to the power of ‘x’ where e=2.718 called
Math.exp(x)
# new – the new operator is used to assign and allocate memory to new objects Euler’s Constant just like pi
and arrays. 15 Math.cbrt(x) Returns the cube root of ‘x’
# instanceof – this operator checks whether the first argument is an instance of 16 Math.log(x) Returns the Natural logarithm of ‘x’
the second argument or not. 17 Returns the integral value of x less than or equal to
e.g. str instanceof String // will return true if str is a String variable Math.floor(x) ‘x’ but datatype returned is double,
Precedence Table hence Math.floor(7.9) will give 7.0
1 (),[] HIGHER PRECEDENCE 18 Returns the integral value of x greater than or equal
2 ++,-- ,~,! | Math.ceil(x) to ‘x’ but datatype returned is double,
3 /,% | hence Math.ceil(7.9) will give 8.0
19 Returns the integral value of x by rounding off the
4 +,- |
Math.rint(x) fractional part to the nearest integer , but data type
5 >>,>>>,<< | returned is double, hence Math.rint(7.9) will give 8.0
6 >,>=,<,<= | 20 Returns the integral value of x by rounding off the
7 ==,!= | Math.round(x) fractional part to the nearest integer, but datatype
8 & | returned is int, hence Math.round(7.9) will give 8
9 | | 21 Generates a double type random number between 0
Math.random()
10 && | to 1
22 This returns the 16 digits precise value of PI(Note
11 || | Math.PI
that it is not a function)
12 ?: V
13 = LOWER PRECEDENCE
>Comment Lines in Java 2. Processing exceptions for components which cannot handle them directly.
// comments — single line comment 3. Processing exceptions for widely used components that should not process their
After the two // characters, Java ignores everything to the end of the line. This is own exceptions.
the most common type of comment. 4. Large Projects that requires uniform error processing.
/* … */ comments — multiple line comment Advantages of exception handling:-
After the /* characters, Java will ignore everything until it finds a */. This kind of 1. It separates error handling code from the normal code.
comment can cross many lines, and is commonly used to “comment out” sections 2. It enhances the readability.
of code — making Java code into a comment while debugging a program. 3. It makes clear and strong program code.
Always write braces. It is good programming style to always write the curly braces, The process of exception handling is implemented using a try … catch block, in
{}, although they are not needed if the clause contains only a single statement. which the try block contains the code which has probability of having errors during
There are two reasons this is good. runtime and the catch block contains code to handle the situation.
• Reliability. When code is modified, the indentation is such a strong indicator of Common Errors
structure that the programmer may not notice that the addition of a statement at 0 < x < 100
the “correct” indentation level really isn’t included in the scope of the if statement. Comparison operators can be used with two numbers. Although you can write 0 < x
This is a surprisingly common error. = or <= instead of ==. For example, because the decimal number 0.1 can not be
• Readability. It is faster to read code with the braces because the reader doesn’t represented exactly in binary, (0.1 + 0.1 + 0.1) is not equal to 0.3
have to keep in mind whether they are dealing with an un-braced single statement String issues using = = and equals ( )
or a braced block. Usually you want to know if the two Strings have the same value, for e.g.
Whitespace (e.g., a blank line, spaces) if (name == “Californication”) // Legal, but SURELY WRONG
Insert blank lines to separate sections of your program. It’s like starting a new Reason is the = = operator is not comparing the values of name and Californication
paragraph in English. The compiler ignores them — it’s for us humans. instead it is just comparing the references i.e. it is checking whether both of them
are strings or not and hence returns true and to the programmer it reveals to be
>Exception Handling in Java perfectly LEGAL. To prove this we can take another e.g. say, –
Exception refers to any contradictory or unusual situation which can be String name = “Californication”;
encountered during a program execution. In Java Exceptions (or Errors) has been System.out.println (name. substring (0,3)); // Gives the output as Cal
categorized broadly under three heading – But when they are compared using = = gives the output as Un-Equal
1. Syntax Errors – A Syntax error occurs when the programmer writes a if (name. substring (0,3) = = “Cal”)
grammatically incorrect code that does not support the rules of programming of System.out.println (“Equal”);
that particular language. This type of error gets detected by the compiler. E.g. else
missing semicolon, using keywords as identifier name, unmatched pair of { }, System.out.println (“Un-Equal”);
undefined functions, undeclared and un-initialized variables etc… Hence always use equals ( ) method of String class to compare the values of String
2. Logical Errors – A Logical error is born out of a programmer who misunderstands class objects.
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 >NaN
integer type number but the programmer writes a code that determines the square No exceptions are generated by floating-point operations. Instead of an
root of the number. interruption in execution, the result of an operation may be positive infinity,
3. Runtime Errors – A Runtime error is shown when a syntactically and logically negative infinity, or NaN (not a number). Division by zero or overflow produces
correct program with a set of inputs which is invalid for a given expression. The infinity. Subtracting two infinities produces a NaN. Infinity. Similarly no exceptions
same expression is valid for another set of values. E.g. int quo = div / n, the are generated for statements like Math.pow(0,–1) and such statements will result
expression is valid for all sets of positive values of n but not if n = 0. in Infinity as output
Exception handling is ideal for –
1. Processing exceptional situations.
>Flow Control in Java Programs }
# If Statement switch
The purpose of the if statement is to make decisions, and execute different parts of The switch keyword is followed by a parenthesized integer expression, which is
your program depending on a boolean true/false value. followed by the cases, all enclosed in braces.. The switch statement executes the
The ‘if’ statement has this form, where condition is true or false case corresponding to the value of the expression. Normally the code in a case
if (condition) 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
… // Do this clause if the condition is true. 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.
Alternative forms of if statements – case
if (condition) 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.
… // Do this clause if the condition is true default
} If no case value matches the switch expression value, execution continues at the
else 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
… // Do this clause if the condition is false because execution just continues out the bottom of switch if this is the last clause.
} break
Always make sure that the number of if clause should not exceed the number of The break statement causes execution to exit to the statement after the end of the
else clause, because it will result in ‘dangling else problem’, in such case make use switch. If there is no break, execution falls through into the next case. Flowing
of if…else if…else construct as shown below – directly into the next case is almost always an error.
if (condition 1) 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
… // Do this clause if the condition is true 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
else if (condition 2) switch should be based on which is more readable.
{ Limitations of switch case
… // Do this clause if the condition is false Java’s switch statement, which was taken directly from C++ to increase its
} attractiveness to C++ programmers, is not well loved.
else • 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
… // Do this clause if the condition is false other languages do.
} • Error-prone. It is error-prone and a common source of bugs – forgetting break or
#switch…case Statement default silently ignores errors. Some languages have eliminated these dangerous
The if statement allows you to select one of two sections of code to execute based situations.
on a boolean value (only two possible values). The switch statement allows you to • Fall through. Another disadvantage of switch…case is that in absence of break
choose from many statements based on an integer (including char) statement in the respective cases will cause the flow control to cascade down and
switch (expr) 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.
case c1: … break; Iteration through Loops
case c2: … break; 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
default: two kinds of looping statements in Java.
1. Entry Controlled Loop The for loop groups these three common parts together into one statement,
2. Exit Controlled making it more readable and less error-prone than the equivalent while loop. For
An Entry Controlled loop which is also known as Pre Tested Loop the condition of repeating code a known number of times, the for loop is the right choice.
the loop is first checked and then the loop body is executed, which means if the There are three clauses in the ‘for’ statement.
condition is false the loop doesn’t get executed even for once. 1. The initialization statement is done before the loop is started, usually to initialize
E.g. a. for LOOP an iteration variable.
b. while LOOP 2. The condition/test expression is tested before each time the loop is done. The
An Exit Controlled loop which is also known as Post Tested Loop the condition is loop isn’t executed if the boolean expression is false (the same as the while loop).
checked at the end of the loop body, which means even if the condition is false the 3. The update statement is done after the body is executed. It typically increments
loop gets executed at least for once. an iteration variable.
E.g. a. do…while LOOP Syntax:
If the body of a loop has more than one statement, you must put the statements for (initialization ; condition/test expression; update)
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 body
the scope of statements. Always using braces allows the reader to relax and not }
worry about the special single statement case. //… For loop to to display squares of natural nos. less than 10
for (int i = 1; i <= 10; i++)
#while statement {
The while statement is used to repeat a block of statements while some condition is System.out.println(i*i);
true. The condition must become false somewhere in the loop, otherwise it will }
never terminate.
Syntax: #do…while statement
initialization; When you want to test at the end to see whether something should be repeated,
while (condition) the do…while statement is the natural choice
{ Syntax
Body; do
update; {
} ...
//… While loop to display squares of natural nos. less than 10 } while (condition);
int i = 1; Always remember that a do…while statement has a semi-colon at its end.
while (i <=10) The for loop is shorter, and combining the initialization, test, and increment in one
{ statement makes it easier to read and verify that it’s doing what you expect. The for
System.out.println(i*i); loop is better when you are counting something. If you are doing something an
i++; indefinite number of times, while loop may be the better choice.
}
>Functions in Java
#for statement A function is a block or portion of code within a larger program which consists of
Many loops consist of three operations surrounding the body: some declarations and executable statements, which performs a specific task and is
(1) initialization of a variable, relatively independent of the remaining code.
(2) testing a condition, and The term method is used alternatively with function and means the same in Java
(3) updating a value before the next iteration. 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’.
Advantages of using Functions – Function prototype
1. To cope with the complexity of code by breaking down complex bigger code into The first line of a function that consists of access specifier, modifier, return type,
smaller and simpler ones. function name and list of parameters enclosed within a pair of parenthesis is called
2. Hiding details (thus implementing Abstraction) function prototype.
3. Reusability of Code A function prototype describes the function interface to the compiler, by giving
4. Makes debugging of errors easy. details of number and type of arguments, return type etc…
e.g.
Anatomy of a function public static void compute(int a, int b)
FUNCTION NAME ( ) {
{ …
Body of the function… …
} }
Let us now see all the components individually – Function signature
1. These are keywords which define the accessibility of the function, if nothing is The function signature is a part of function prototype; it basically refers to the
mentioned then by default it is ‘friendly’ friendly is not a keyword. They are of 4 argument list i.e. number, order and type of arguments.
types e.g.
a. Public public static void compute(int a, int b)
b. private {
c. protected …
d. friendly this is not a keyword and hence cannot be written explicitly. …
}
2. These are keywords which redefines the functionality within the methods. They
can be final, native, static, synchronized, transient, volatile etc… public & private
In a function the access specifier indicate the scope of visibility of that particular
3. They specify what type of value a function can return, hence they can be of any function, this means whether the data members and member methods are
primitive of reference data types like int, byte, float, char, String or even class types. accessible only within the class, or other classes within the same package or other
In case the function doesn’t return any value the keyword ‘void’ is used. classes in other packages.
Public members are accessible everywhere, within the same class as well as inside
4. Function name – This can be any valid identifier, but it is always advisable to take other classes that inherits the base class or by creating objects of the former class in
logical and meaningful names, it should conventionally begin with a lowercase the latter one even if they do not inherit, but private members are accessible only
letter and in case of multiple words join the words and begin each word in within the same class.
Uppercase except for the first word.
e.g. toUpperCase( ) static
A static data member is also known as a class variable, such variables have only one
5. This is a comma separated list of variables along with associated data types. This instance inside the class and we can not create multiple instances through multiple
list can also be empty which indicates the function is non–argumentative. objects.
e.g. On the other hand if a member is non-static then such members are called instance
public static void add(int a, int b) variables, which mean we can have multiple instances of such variables through
{ multiple objects.
… e.g.
} class Exmp1
{
int x; // non-static or instance variable which can have multiple instances e.g.
static int y; // static variable or class variable which has only one instance public static void main( )
public static void main( ) {
{ int x = 10, y = 20;
Exmp1 obj1 = new Exmp1( ); actual parametersadd (x, y);
Exmp1 obj2 = new Exmp1( ); // three different objects through which we can }
Exmp1 obj3 = new Exmp1( ); // have three different values of ‘x’ formal parameterspublic static void add(int x, int y)
obj1.x=10; {
obj2.x=20; // the same variable ‘x’ has three different values simultaneously System.out.println(x+y);
obj3.x=30; }
y = 100; // the variable ‘y’ being static is accessed directly and can have only A function be of one of the four types depending on its argument list and return
// one value type –
obj1.y=100; 1. Non-argumentative & non-return type
obj2.y=200; // even if we try to access the variable ‘y’ through different objects Example
obj3.y=300; // the same ‘y’ gets overwritten and finally the last value prevails class ABCD
}} {
So, we see that if a member is static in nature it will have only one copy in the public static void main( )
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 display( );
which instance we are referring to as it has multiple occurrences. }
public static void display( )
>How to access a function? {
A function can be accessed or invoked from other functions by simply writing the System.out.println(“Loyola School”);
name of the function along with the argument list (if any) otherwise the argument }
list is kept empty. }
e.g.
class ABCD 2. Argumentative & non-return type
{ Example
public static void main( ) class ABCD
{ {
int x = 10, y = 20; public static void main( )
function calladd (x, y); {
} int x = 10;
public static void add(int x, int y) display(x);
{ }
System.out.println(x+y); public static void display(int x)
} {
} System.out.println(“The value of x =” + x);
Actual & Formal Parameters / Arguments }
The actual parameters are those that appear at the point of function invocation or } // Note that a function which is void cannot return any value
function call are called Actual parameters.
The formal parameters are those that appear at the point of function declaration or 3. Non-argumentative & return type
function signature are called Formal parameters. Example
class ABCD call( );
{ }
public static void main( ) public static void call( )
{ {
int x = display( ); System.out.println(“Inside the method call”);
System.out.println(“The value of x =” + x); return ; // return statement has nothing following it
} }
public static int display( ) }
{ Three types of functions:
int x = 10; 1. Computational functions – The functions that computes or calculates certain
return x; values or quantities and returns the answer to the calling method is called
} Computational function.
} // Note that the return type of the function and the variable associated e.g. Math.pow(a,b);
// with the keyword return must be identical, also note that the function 2. Manipulative functions – The functions which manipulates the data and returns
// at the point of invocation gets equated with a similar datatype. information to the calling function as success or failure code in the form of 0 & 1 or
4. Argumentative & return type true & false.
Example e.g. Character.isLetter( )
class ABCD 3. Procedural Functions – The functions that perform certain tasks like reading from
{ source files, reading from terminals, displaying data to the terminal are called
public static void main( ) procedural functions. They generally do not have any return type.
{ e.g. System.out.println( );
int x = 10; Pure & Impure functions
int y = display( x ); A pure function is one that takes objects and/or primitive data as arguments but
System.out.println(“The square value of x =” + y); 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
public static int display(int x) known as Accessor methods.
{ An impure function on the other hand modifies the state of its objects or
int y = x * x; arguments. They are also known as Modifier methods.
return y; Pure Functionpublic static int maximum(int a, int b)
} {
} int c = Math.max(a,b);
The return statement return c;
A function terminates as soon as the last statement of the function is encountered }
or the return keyword is encountered. Impure Functionpublic static int product(int a)
It is not necessary that return keyword should be used only in functions that has a {
return type, even functions that are void can use the return keyword to terminate a = a * a;
the function and shift the program control to the calling function but make sure return a;
that the return statement does not have anything preceding the keyword ‘return’. }
e.g.
class ABCD >Function Overloading
{ A function name having several definitions in the same scope that are differentiated
public static void main( ) on the basis of function signature i.e. number of arguments, order of arguments,
{
type of arguments is said to be an overloaded function and the process of creating A constructor that accepts no parameters are called non
such functions is called Function Overloading. parameterized constructors, non parameterized constructors that initialize the
Function overloading implements Polymorphism. instance variables to zero, null and empty values are called Default
e.g. Constructors. Above is an example of default constructor.
class Overload A parameterized constructor accepts parameters or values in its argument list
{ which initialize the various instance data members of the class.
public static void area(int s)
{ class Constr
System.out.println(“Area of square =” + (s*s)); {
} int n;
public static void area(int l, int b) Constr(int val)
{ {
System.out.println(“Area of rectangle =” + (l*b)); n = val;
} } // invokes the constructor
public static void area(double r) public static void main( )
{ { int v = 25;
System.out.println(“Area of circle =” + (3.1415 * r * r)); Constr obj = new Constr(v);
} }
} }

>Constructors in Java >Exception Handling


A Constructor is a member method of a class which has same name as that of a An exception in general is any unexpected / contradictory situation of error
class; has no return type not even void, used to initialize the instance variables of a encountered at the time of program execution is called an Exception.
class, and gets invoked automatically as soon as the object of the class is created. Types of Errors
class Constr 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
int n; at the time of program compilation.
Constr( ) e.g. int class = 10; // class is a keyword hence syntactically incorrect
{ Run time errors – The errors that occurs during program execution is called run
n = 0; time errors. These unexpected errors may occur due to array index going out of
} // invokes the constructor bound, end of file reached, type mismatch errors at the time of data input etc…
public static void main( ) 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.
Constr obj = new Constr( ); Such errors are very difficult to detect, like if the problem says to add two numbers
System.out.println(obj.n); 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.
Types of Constructors Understanding try / catch / finally blocks and throws keywords
#Non Parameterized Constructors Try block contains the code which might lead to run time errors.
#Parameterized Constructors 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 and converting primitives and String objects to and from different bases (or radix),
handle the exception. such as binary, octal, and hexadecimal.
Throws is a keyword which is used to inform that an error has occurred, it is Wrapper Class functions / methods
specified in the line of function definition (prototype). The wrapper class methods that are static in nature can be directly accessed as –
The program below gives an idea as to how an Exception is handled in Java Class_name.method_name (arguments) e.g. Boolean.toString(b);
Boolean Wrapper class
class Error Function Description
{
public void testfunction (int x, int y) throws Exception booleanValue( ) Convert Boolean object to boolean primitive datatype.
{
valueOf( ) Convert String to Boolean object.
int z;
try toString( ) Convert Boolean object to String.
{ Byte Wrapper class
z = x / y;
Function Description
System.out.println( z );
} parseByte( ) Converts String to byte primitive datatype.
catch (exception exp)
{ valueOf( ) Converts String to Byte object.
System.out.println(exp.getMessage( ) ); toString( ) Converts byte primitive to String object.
}
Short Wrapper class
finally
{ Function Description
System.out.println(“Un–reported exception has occurred…”); parseShort( ) Converts String to short primitive datatype.
}
} valueOf( ) Converts String to Short object.
toString( ) Converts short primitive to String object.
>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 Integer Wrapper class
include the primitive datatypes in the family of objects by using what are Function Description
called wrapper classes.
parseInt( ) Converts String to int primitive datatype.
Wrapper classes wrap the primitive datatypes into respective objects.
There is a wrapper class for every primitive date type in Java. This class valueOf( ) Converts String to Integer object.
encapsulates a single value for the primitive data type. For instance the wrapper
class for int is Integer, for float is Float, and so on. toString( ) Converts int primitive to String object.
Wrapper classes are a part of Java’s standard default library java.lang Long Wrapper class
The wrapper classes in the Java API serve two primary purposes: Function Description
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 parseLong( ) Converts String to long primitive datatype.
Collections, or returned from a method with an object return value.
valueOf( ) Converts String to Long object.
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, toString( ) Converts long primitive to String object.
Float Wrapper class System.out.println(s1.concat(“Application”); // returns ComputerApplication
Function Description But, if we try to print the String s1 after the above implementation we will find
that System.out.println(s1); // returnsComputer which clearly states that the s1
parseFloat( ) Converts String to float primitive datatype. string was
//not modified…
valueOf( ) Converts String to Integer object.
Strings can be created in two ways –
toString( ) Converts int primitive to String object. As a String Literal
Double Wrapper class As a String object
A String Literal can be created as follows –
Function Description
String str = “Welcome”;
parseDouble( ) Converts String to double primitive datatype. 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
valueOf( ) Converts String to Double object. is returned.
toString( ) Converts double primitive to String object. e.g.
String str1 = “Welcome”; // a new string is created in the String Pool
Character Wrapper class
String str2 = “Welcome”; // no new string is created as “Welcome” already exists in
Function Description pool
A String Object can be created using a new keyword –
isLetter( ) Checks whether the specified character is a Letter or not.
String str = new String (“Welcome”);
isDigit( ) Checks whether the specified character is a Digit or not. 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
isWhiteSpace( ) Checks whether the specified character is a blank or not.
concatenating strings, comparing strings, extracting characters from string, creating
Checks whether the specified character is in uppercase or substrings from given strings, replacing characters from within a string, etc…
isUpperCase( )
not. String class functions
Checks whether the specified character is in lowercase or String Functions Return Description
isLowerCase( )
not. 1 length( ) int Returns length of a string
toUpperCase( ) Converts the specified character to Uppercase. Returns a character at a position k
2 charAt(k) char
toLowerCase( ) Converts the specified character to Lowercase. within the string.

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

Das könnte Ihnen auch gefallen