Академический Документы
Профессиональный Документы
Культура Документы
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
1
Object
Object: is a bundle of related variables and functions (also known methods).
Objects share two characteristics: They have State and Behavior.
State: State is a well-defined condition of an item. A state captures the relevant aspects of an
object
Behavior: Behavior is the observable effects of an operation or event,
Examples:
eg1:
Object:House
State:Current Location,Color, Area of House etc.
Behavior: Close/Open main door.
eg 2:
Object: – Car
State: Color, Make
Behavior: Climb Uphill, Accelerate, Slowdown etc
Note: Everything a software object knows (State) and can do (Behavior) is represented by
variables and methods (functions) in the object respectively.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. It
also means hiding data and methods within an Object. For example: capsule, it is wrapped with
different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
.
2
Encapsulation provides the security that keeps data and methods safe from inadvertent
changes. Programmers sometimes refer to encapsulation as using a “black box,” or a device
that you can use without regard to the internal mechanisms.
A programmer can access and use the methods and data contained in the black box but cannot
change them.
Inheritance
Inheritance is mainly used for code reusability. So you are making use of already written the
classes and further extending on that. In general, when one object acquires all the properties
and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used
to achieve runtime polymorphism.
Polymorphism
In Core, Java Polymorphism is one easy concept to understand.Polymorphism definition is that
Poly means many and morphs’ means forms. When one task is performed by different ways i.e.
known as polymorphism.
It describes the feature of languages that allows the same word or symbol to be interpreted
correctly in different situations based on the context. There are two types of Polymorphism
available in Java.
For example, in English, the verb “run” means different things if you use it with “a footrace,” a
“business,” or “a computer.” You understand the meaning of “run” based on the other words
used with it. Object-oriented programs are written so that the methods having the same name
works differently in different context. Java provides two ways to implement polymorphism.
3
Dynamic Polymorphism (run time polymorphism/ Method Overriding):
When you create a subclass by extending an existing class, the new subclass contains data
and methods that were defined in the original superclass. In other words, any child class object
has all the attributes of its parent. Sometimes, however, the superclass data fields and methods
are not entirely appropriate for the subclass objects; in these cases, you want to override the
parent class members in order to invoke them.
Abstraction
All programming languages provide abstractions.In java, we use abstract class and interface to
achieve abstractionHiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.
A powerful way to manage abstraction is through the use of hierarchical classifications. This
allows you to layer the semantics of complex systems, breaking them into more manageable
pieces. From the outside, a car is a single object. Once inside, you see that the car consists of
several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so
on. In turn, each of these subsystems is made up of more specialized units. For instance, the
sound system consists of a radio, a CD player, and/or a tape player. The point is that you
manage the complexity of the car (or any other complex system)through the use of hierarchical
abstractions.
An abstract class is something which is incomplete and you cannot create an instance of the
abstract class. If you want to use it you need to make it complete or concrete by extending it. A
class is called concrete if it does not contain any abstract method and implements all abstract
method inherited from abstract class or interface it has implemented or extended.By the way,
4
Java has a concept of abstract classes, abstract method but a variable cannot be abstract in
Java.
HISTORY OF JAVA
• JAVA is language that has evolved from C++ which is a direct descendant of C. Most of
the characters of JAVA is inherited from C and C++.
Derives its Syntax from C.
Object oriented features influenced by C++.
• Java was conceived by James Gosling (popularly known as “Creator of Java”), Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc.in
1991.
• It took 18 months to develop the first working version. This was initially named “Oak” but
was renamed as “JAVA” in 1995.
• JAVA is platform independent programming language, which provides developers with
the means to create powerful applications
• Although the Java programming language is usually associated with World Wide Web,
its primary motivation was to develop a language which is platform - independent(i.e.,
architecture neutral) that could be used to create software to be embedded in various
consumer electronic devices, such as microwave ovens and remote controls.
Reasons Which Led To JAVA Language Development
To create software to be embedded in various consumer electronic devices many CPUs are
used as controllers. The problem with C and C++ is that they are designed to be compiled for
aspecifictarget.
Even though C++ programs can be developed for any type of CPU, to do so it requires a full
C++ compiler targeted for that CPU. The problem here is compilers are expensive and time
5
consuming to create.
To overcome this the work began on developing a portable, platform-independent
language that could be used to produce code that run on a variety of CPUs under differing
environments, which led to the creation of JAVA.
World Wide Web also took shape at the same time Java was implemented. With the
emergence of WWW, Java was propelled to the forefront of computer language design,
because the Web also demanded portable programs.
Why Java was Successful?
JAVA was designed, tested and refined by real, working programmers.
1. JAVA is cohesive and logically consistent.
2. JAVA gives the programmer, full control. It’s a language for professional
programmers.
JAVA BYTECODE
• Byte code is a highly optimized set of instructions designed to be executed by the
Java run-time system, which is called the Java Virtual Machine (JVM).
• JVM is an Interpreter for Byte code.
THE JAVA VIRTUAL MACHINE
The JVM is a virtual computer that resides in memory only.
Translating a program into byte code makes it easier to run a program in a wide
variety of environments.
Reason: Only the JVM needed to be implemented for each platform.
The Java programs are compiled for the JVM is what makes the language so
unique but in order for java programs to run on a particular platform, the JVM must
be implemented for that platform.
The JVM is the reason why Java is Portable. It provides a layer of Abstraction
between the compiled Java Program and the underlying hardware platform and
operating system.
JAVA TECHNOLOGY IS BOTH A PROGRAMMING LANGUAGE AND A PLATFORM.
JAVA PROGRAMMING LANGAUGE
With most programming languages, you either compile or interpret a program so
that you can run it on your computer. The Java programming language is unusual in
that a program is both compiled and interpreted.
6
With the compiler, first you translate a program into an intermediate language called
Java bytecodes —the platform-independent codes interpreted by the interpreter on
the Java platform. The interpreter parses and runs each Java bytecode instruction
on the computer.
Compilation happens just once; interpretation occurs each time the program is
executed.
The following figure illustrates how this works.
You can think of Java bytecodes as the machine code instructions for the Java Virtual
Machine (Java VM). Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the Java VM.
Java bytecodes help make "write once, run anywhere" possible. You can compile your
program into bytecodes on any platform that has a Java compiler. The bytecodes can
then be run on any implementation of the Java VM. That means that as long as a
computer has a Java VM, the same program written in the Java programming language
can run on Windows 2000, a Solaris workstation, or on an iMac.
7
The Java platform differs from most other platforms in that it's a software-only
platform that runs on top of other hardware-based platforms.
The Java platform has two components:
1. The Java Virtual Machine (Java VM) -- (Already exaplained)
2. The Java Application Programming Interface (Java API)
The Java API is a large collection of ready-made software componentsthat provide many useful
capabilities, such as graphical user interface(GUI) widgets.
The Java API is grouped into libraries of related classes and interfaces; these libraries
are known as packages.
The following figure depicts a program that's running on the Java platform. As the
figure shows, the Java API and the virtual machine insulate the program from the
hardware.
Native code is code that after you compile it, the compiled code runs on a specific
hardware platform. As a platform-independent environment, the Java platform can
be a bit slower than native code. However, smart compilers, well-tuned interpreters,
and just-in-time byte code compilers can bring performance close to that of native
code without threatening portability.
JAVA BUZZWORDS
The Java programming language is a high-level language that can be characterized by all of
the following buzzwords:
Simple Architecture neutral
Object oriented Portable
Distributed High performance
Interpreted Multithreaded
Robust Dynamic
Secure
8
IMPLEMENTING A JAVA PROGRAM
Implementation of a Java application program consists of series of steps.
1. Create a source file. A source file contains text, written in the Java programming
language, that you and other programmers can understand. You can use any text editor
to create and edit source files.
Save the source code file with .java extension.
2. Compile the source file into a byte code file. The compiler, javac, takes your source file
and translates its text into instructions that the Java Virtual Machine (Java VM) can
understand. The compiler converts these instructions into a byte code file.
To compile the program, run java compiler with the name of the source file in command
line:
javac <filename>.java
3. Run the program contained in the byte code file. The Java interpreter installed on your
computer implements the Java VM. This interpreter takes your byte code file and
carries out the instructions by translating them into instructions that your computer can
understand. At the command prompt to run a stand-alone Java Program, use java
interpreter, type :
java <filename>
When executed the program displays the output.
Where, <filename> -- user defined filename.
JAVA PROGRAM STRUCTURE
Java Program may contain many classes of which only one class defines the main method.
A Java Program may contain one or more sections.
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions
9
Main Method Calss
{
Main Method Definition
}
Of the above Sections shown in the figure, the Main Method class is Essential part,
Documentation Section is a suggested part and all the other parts are optional.
Documentation Section
It Comprises a Set of comment lines giving the name of the program, the author and
other details.
Comments help in Maintaining the Program.
Java uses a Style of comment called documentation comment.
/* * …… */
This type of comment helps is generating the documentation automatically.
Package Statement
The first statement allowed in a Java file is a package statement. It declares the
package name and informs the compiler that the classes defined belong to this
package.
Example:
package student;
It is an optional declaration.
Import Statements
The statement instructs the interpreter to load a class contained in a particular
package.
Example : import student.test;
Where, student is the package and test is the class.
Interface Statements
An interface is similar to classes which consist of group of method declaration.
It is used when we want to implement the feature of Multiple Inheritance in Java
It is an optional declaration.
Class Definitions
A Java Program can have any number of class declarations.
10
The number of classes depends on the complexity of the program.
Main Method Class
Every Java Stand-alone program requires a main method as its starting point.
A Simple Java Program will contain only the main method class.
It creates objects of various classes and uses those objects for performing various
operations.
When the end of main is reached the program terminates and the control
transferred back to the Operating system.
VARIABLES
A Variable is a named piece of memory that is used for storing data in java Program.
An object stores its state in variables.
A variable is an identifier used for storing a data value.
Definition: A variable is an item of data named by an identifier.
A Variable may take different values at different times during the execution if the program,
unlike the constants.
We must explicitly provide a name and a type for each variable you want to use in your
program. The variable's name must be a legal identifier --an unlimited series of Unicode
characters that begins with a letter. You use the variable name to refer to the data that the
variable contains.
The variable's type determines what values it can hold and what operations can be
performed on it.
General form of variable declaration :
type name
In addition to the name and type that you explicitly give a variable, a variable has scope.
Example of Variable names :
average
height
total height
classStrength
Rules followed for variable names ( consist of alphabets, digits, underscore and dollar
characters)
11
1. They must not begin with digits.
2. Uppercase and lowercase are not the same. Example: Total and total are two variables
which are distinct.
3. It should not be a keyword.
4. Whitespace is not allowed.
5. Variable names can be of any length.
EXAMPLE PROGRAM
The MaxVariablesDemo program, shown below, declares eight variables of different types
within its main method. The variable declarations are bold:
public class MaxVariablesDemo {
public static void main(String args[]) {
// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = 'S';
boolean aBoolean = true;
// display them all
System.out.println("The largest byte value is " + largestByte);
System.out.println("The largest short value is " + largestShort);
System.out.println("The largest integer value is " + largestInteger);
System.out.println("The largest long value is " + largestLong);
System.out.println("The largest float value is " + largestFloat);
System.out.println("The largest double value is " + largestDouble);
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper case.");
} else {
12
System.out.println("The character " + aChar + " is lower case.");
}
System.out.println("The value of a Boolean is " + aBoolean);
}
}
OUTPUT
The largest byte value is 127
The largest short value is 32767
The largest integer value is 2147483647
The largest long value is 9223372036854775807
The largest float value is 3.40282e+38
The largest double value is 1.79769e+308
The character S is upper case.
The value of a Boolean is true
SCOPE AND LIFETIME OF VARIABLES
Java allows variables to be declared in any block. A block defines a scope.
Each time when we start a new block we are starting a new scope.
Scope determines what objects are visible to other parts of the program and
also determines the lifetime of those objects.
Two major scopes in Java are
Defined by a class.
Defined by a method.
The Scope defined by a method begins with its opening curly brace. As a
general rule, a variable declared inside a scope are not visible to the code that
is defined outside the scope.
Final Variables
o You can declare a variable in any scope to be final. The value of a final variable
cannot change after it has been initialized. Such variables are similar to
constants in other programming languages.
o To declare a final variable, use the final keyword in the variable declaration
before the type:
final int aFinalVar = 0;
13
o The previous statement declares a final variable and initializes it, all at once.
Subsequent attempts to assign a value to aFinalVar result in a compiler error.
o A final local variable that has been declared but not yet initialized is called a
blank final. Again, once a final local variable has been initialized, it cannot be
set, and any later attempts to assign a value to blank final result in a compile-
time error.
DATA TYPES
Every variable must have a data type. A variable's data type determines the values that the
variable can contain and the operations that can be performed on it.
Data types in Java are of two types:
1. Primitive Types( Intrinsic or built-in types )
2. Derived Types (Reference Types).
The following table lists, by keyword, all of the primitive data types supported by the
Java platform, their sizes and formats.
(integers)
(real numbers)
14
point
(other types)
16-bit Unicode
char A single character
character
Arrays, classes, and interfaces are reference types. The value of a reference type variable,
in contrast to that of a primitive type, is a reference to (an address of) the value or set of
values represented by the variable.
A reference is called a pointer or a memory address in other languages. The Java
programming language does not support the explicit use of addresses like other languages
do. You use the variable's name instead.
OPERATORS
Operators are used in programs for manipulating data and variables.
An operator performs a function on one, two, or three operands.
An operator that requires one operand is called a unary operator.
For example, ++ is a unary operator that increments the value of its operand by 1.
An operator that requires two operands is a binary operator.
For example, = is a binary operator that assigns the value from its right-hand operand to its
left-hand operand.
A ternary operator is one that requires three operands. The Java programming language
has one ternary operator?:
The various categories of operators are as follows:
• Arithmetic Operators
• Relational and Conditional Operators
• Shift and Logical Operators
15
• Assignment Operators
• Other Operators
♦ Arithmetic Operators
The following table lists the basic arithmetic operators provided by the Java
programming language. Except for +, which is also used to concatenate strings, these
operators can be used only on numeric values.
16
Unary Arithmetic Operators
Relational Operators
> op1 > op2 Returns true if op1 is greater than op2
>= op1 >= op2 Returns true if op1 is greater than or equal to op2
< op1 < op2 Returns true if op1 is less than op2
<= op1 <= op2 Returns true if op1 is less than or equal to op2
!= op1 != op2 Returns true if op1 and op2 are not equal
You can use the following conditional operators to form multi-part decisions.
Conditional Operators
&& op1 && op2 Returns true if op1 and op2 are both true; conditionally evaluates op2
|| op1 || op2 Returns true if either op1 or op2 is true; conditionally evaluates op2
& op1 & op2 Returns true if op1 and op2 are both boolean and both true; always
17
evaluates op1 and op2; if both operands are numbers, performs
bitwise AND operation
Returns true if both op1 and op2 are boolean and either op1 or op2 is
| op1 | op2 true; always evaluates op1 and op2; if both operands are numbers,
performs bitwise inclusive OR operation
Returns true if op1 and op2 are different — that is, if one or the other
^ op1 ^ op2
of the operands, but not both, is true
Shift Operators
Shift bits of op1 left by distance op2; fills with zero bits on the right-
<< op1 << op2
hand side
Shift bits of op1 right by distance op2; fills with highest (sign) bit on
>> op1 >> op2
the left-hand side
Shift bits of op1 right by distance op2; fills with zero bits on the left-
>>> op1 >>> op2
hand side
Logical Operators
& op1 & op2 Bitwise AND if both operands are numbers;
18
conditional AND if both operands are boolean
♦ Assignment Operators
The basic assignment operator looks as follows and assigns the value of op2 to op1.
op1 = op2;
In addition to the basic assignment operation, the Java programming language defines these
short cut assignment operators that perform an operation and an assignment using one
operator.
19
>>>= op1 >>>= op2 op1 = op1 >>> op2
Other Operators
op1 ? op2 :
?: If op1 is true, returns op2. Otherwise, returns op3.
op3
Creates and array with op1 elements. Must be used with the new
[] type[ op1 ]
operator.
Accesses the element at op2 index within the array op1. Indices
[] op1[ op2 ]
begin at 0 and extend through the length of the array minus one.
op1 instanceof
instanceof Returns true if op1 is an instance of op2
op2
20
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator: For example, x =
7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence
appear at the top of the table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators will be evaluated first.
Control Statements:
Programming languages provide various control structures that allow for more complicated
execution paths.
Java programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non zero value.When executing, if the boolean_expression
result is true, then the actions inside the loop will be executed. This will continue as long as the
expression result is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 15 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This will produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
for Loop in Java
A for loop is a repetition control structure that allows you to efficiently write a loop that
22
needs to be executed a specific number of times. A for loop is useful when you know how many
times a task is to be repeated.
Syntax
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables and this step ends with a semi colon (;).
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop will not be executed and control jumps to the next
statement past the for loop.
After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This
statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example :
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 15; x = x+1)
{ System.out.print("value of x : " + x );
System.out.print("\n");
}
}}
This will produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
23
value of x : 14
Do While Loop in Java
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the
loop execute once before the Boolean is tested. If the Boolean expression is true, the control
jumps back up to do statement, and the statements in the loop execute again. This process
repeats until the Boolean expression is false.
Example :
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 15 );
}
}
This will produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
24
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Java supports the
following control statements.
25
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes control to immediately jump to the update
statement.
• In a while loop or do/while loop, control immediately jumps to the Boolean expression.
Syntax
continue;
Example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 )
{ continue; }
System.out.print( x+ “ “ );
}
}
}
This will produce the following result:
10 20 40 50
Decision Making
Java programming language provides following types of decision making statements.
26
If Statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if (Boolean_expression)
{ //Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not, the first set of code after the end of the if statement (after the closing curly
brace) will be executed.
Example
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ) { System.out.print("This is if statement"); }
}
}
Output :
This is if statement.
If-else Statement
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax
if (Boolean_expression)
{ //Executes when the Boolean expression is true }
else
{ //Executes when the Boolean expression is false }
If the boolean expression evaluates to true, then the if block of code will be executed,
27
otherwise else block of code will be executed.
Example
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ) { System.out.print("This is if statement"); }
else
{ System.out.print("This is else statement"); }
}
}
Output :
This is else statement
The if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if, else if, else statements there are a few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
if (Boolean_expression 1)
{ //Executes when the Boolean expression 1 is true }
else if (Boolean_expression 2)
{ //Executes when the Boolean expression 2 is true }
else if (Boolean_expression 3)
{ //Executes when the Boolean expression 3 is true }
else
{ //Executes when the none of the above condition is true }
Example
public class Test {
public static void main(String args[]){
int x = 30;
28
if( x == 10 ) { System.out.print("Value of X is 10"); }
else if( x == 20 ) { System.out.print("Value of X is 20"); }
else if( x == 30 ) { System.out.print("Value of X is 30"); }
else { System.out.print("This is else statement"); }
}
}
Output :
Value of X is 30
Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax
switch(expression)
{
case value : //Statements break;
//optional
case value : //Statements break;
//optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:
• The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
Example
public class Test {
29
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' : System.out.println("Excellent!"); break;
case 'B' :
case 'C' : System.out.println("Well done"); break;
case 'D' : System.out.println("You passed");
case 'F' : System.out.println("Better try again"); break;
default : System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Output:
Well done
Your grade is C
The ? : Operator:
Conditional operator ? : can be used to replace if...else statements. It has the following general
form:
Exp1 ? Exp2 : Exp3 ;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
To determine the value of the whole expression, initially exp1 is evaluated.
• If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
• If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of
the entire expression.
ARRAYS
An array is simply a sequence of either objects or primitives all the same type and
packaged together under one identifier name.
30
An array is a structure that holds multiple values of the same type. The length of an array is
established when the array is created (at runtime). After creation, an array is a fixed-length
structure.
An array element is one of the values within an array and is accessed by its position within
the array.
Arrays are useful for grouping related information.
Declaring a Variable to Refer to an Array
To create an array, we have to first create an array variable of desired type.
General Syntax of Array Declaration
type var-name[];
or
type[] var-name;
Where, type declares the base type of the array.
Example
int[] anArray; // declare an array of integers
An array declaration has two components:
Array's type
Array's name.
Creating an Array
Arrays are created explicitly using Java's new operator.
The next step is allocating an array with enough memory for ten integer elements
and assigns the array to the variable anArray declared earlier.
anArray = new int[10]; // create an array of integers
when creating an array, we use the new operator, plus the data type of the array
elements, plus the number of elements desired enclosed within square brackets ('['
and ']').
Syntax
new elementType[arraySize]
EXAMPLE PROGRAM
public class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declare an array of integers
31
anArray = new int[10]; // create an array of integers
// assign a value to each array element and print
for (int i = 0; i < anArray.length; i++) {
anArray[i] = i;
System.out.print(anArray[i] + " ");
}
System.out.println();
}
}
32
Objects and classes in Java-class fundamentals-declaring objects-defining classes-
access specifiers – constructors- methods-inheritance-Method overriding-abstract
classes-using final with inheritance.
Class and objects:
A class is nothing but a blueprint or a template for creating different objects which
defines its properties and behaviors. Java class objects exhibit the properties and behaviors
defined by its class. A class can contain fields and methods to describe the behavior of an
object.
o fields
o methods
o constructors
o blocks
o nested class and interface
An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tengible and intengible). The example of
integible object is banking system.
33
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.
For Example:
Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used
to write, so writing is its behavior.
Object Definitions:
The new keyword is used to allocate memory at run time. It creates a Java object and
allocates memory for it on the heap. new is also used for array creation, as arrays are also
objects.
Eg:
It creates an object of the Rectangle class. This statement has three parts:
1. Declaration:
Declarations notify the compiler that name to refer to a variable whose type
is type. Declarations do not create new objects.
type name;
where type is the data type of the object and name is the name to be used for
the object.
Eg:
Rectangle rect;
34
2. Instantiation: The new keyword is a Java operator that creates the object.
Eg:
new Rectangle();
Eg:
Private access modifier is the most restrictive access level. Class and interfaces cannot
be private.
Example:
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Public Access Modifier (least restrictive)
A class, method, constructor, interface, etc. declared public can be accessed from any
other class. Therefore, fields, methods, blocks declared inside a public class can be accessed
from any class belonging to the Java Universe.
36
However, to access public class in a different package, then the public class still needs
to be imported. Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.
Example:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Default Access Modifier
Any modifier is not specified, and then it is treated as default by default. The default
modifier is accessible only within package.
Example:
//save by A.java
37
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class and interface.
Example:
//save by A.java
package pack;
public class A
{
protected void msg()
{
38
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Java Access Modifiers Table for Class and Interface:
39
Within Same Class Yes Yes Yes Yes
Methods in Java
Method describe behavior of an object. A method is a collection of statements that are
group together to perform an operation.
Syntax :
Modifier return-type methodName(parameter-list)
{
//body of method
}
Modifier : Modifier are access type of method.
Return Type : A method may return value. Data type of value return
by a method is declare in method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
40
Eg:
public double circleArea(double r)
{
double area;
area=3.14*r*r;
return area;
}
Example:To Find Minimum among two values
public class Minimum
{
int mini(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
public static void main(String[] args)
{
int a = 11;
int b = 6;
Minimum o=new Minimum();
int c = o.mini(a, b);
System.out.println("Minimum Value = " + c);
}
}
Parameters Passing:
There are two ways to pass an argument to a method
Call by value
41
Call by reference
Call by Value:
In this approach copy of an argument value is pass to a method. The changes being
done in the called method, is not affected in the calling method.
Example:
public class Test
{ public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(“x=”+x);
}
}
Output: x=50
Call-by-Reference :
In this reference of an argument is pass to a method. Any changes made inside the
method will affect the agrument value.
Example:
public class Test
{
int x=10;
int y=20;
public void callByReference(Test t)
{
t.x=100;
t.y=50;
}
public static void main(String[] args)
42
{
Test ts = new Test();
System.out.println("Before "+ts.x+" "+ts.y);
ts.callByReference(ts);
System.out.println("After "+ts.x+" "+ts.y);
}
}
Output:
Before 10 20
After 100 50
Method Overloading in Java
If a class has multiple methods by same name but different parameters, it is known
as Method Overloading. Method overloading is also known as Static Polymorphism.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In this example, class calculation has two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition of three numbers.
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Example of Method Overloading by changing data type of argument:
43
In this example, class calculation2 have two overloaded methods that differs in
data type. The first sum method receives two integer arguments and second sum method
receives two double arguments.
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
44
Example of Method Overloading with TypePromotion:
class OverloadingCalculation1
{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);// second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Constructors:
Constructor in java is a special type of method that is used to initialize the object.
45
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object. Constructor in Java cannot be abstract, static, final or
synchronized.
1) Default constructor
2) No-argument constructor
3) Parameterized constructor
Default Constructor
If any constructor not defined in class, java generates one constructor at the time of
object creation by default. This constructor is known as default constructor.
Default constructor provides the default values to the object like 0, null etc. depending
on the type.
<class_name>()
{
}
class Bike
{
Bike()
{
}
public static void main(String args[])
{
Bike b=new Bike();
}
}
No-argument constructor
46
Constructor with no arguments is known as no-argument constructor. The signature is
same as default constructor, however body can have any code unlike default constructor where
the body does nothing.
Example:
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
}
Parameterized constructor
Constructor overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
47
class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.
48
}
Types of inheritance
Single Inheritance
Multiple Inheritance (Through Interface)
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance (Through Interface)
Single Inheritance
Single Inheritance is the simple inheritance of all, When a class extends another
class(Only one class) then it called as Single inheritance. The below diagram represents the
single inheritance in java where Class B extends only one class Class A. Here Class B will be
the Sub class and Class A will be one and only Super class.
Example
Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages
such as Java, Small Talk, C# etc..(C++ Supports Multiple Inheritance). As the Child class has
to manage the dependency of more than one parent class. But using interfaces multiple
inheritance is achieved in Java.
Multilevel Inheritance
In Multilevel Inheritance a derived class will be inheriting a parent class and as well
as the derived class act as the parent class to other class. As seen in the below
diagram. ClassB inherits the property of ClassA and again ClassB act as a parent
for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.
50
MultiLevel Inheritance Example
Hierarchical Inheritance
In Hierarchical inheritance one parent class will be inherited by many sub classes. As
per the below example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will be
acting as a parent class for ClassB, ClassC and ClassD.
51
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
52
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();
//Assigning ClassD object to ClassD reference
ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface only it is
achieved. Flow diagram of the Hybrid inheritance will look like below. ClassA will be acting as
the Parent class for ClassB & ClassC and ClassB & ClassC will be acting as Parent for ClassD.
Super Keyword:
The super keyword in java is a reference variable which is used to refer immediate
parent class object.
Whenever creating the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
53
It is used inside a sub-class method definition to call a method defined in the super
class. Private methods of the super-class cannot be called. Only public and protected
methods can be called by the super keyword.
Syntax:
super. variablename;
super . <method-name>();
Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
It will invoke derived class run method only. Invoke run method of base class by using
reference type.
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
55
{
Vehicle obj = new Vehicle(); //Vehicle reference and Vehicle object
Vehicle obj1 = new Bike(); //Vehicle reference but Bike object
obj.run();
obj1.run();
}
}
Output:
Vehicle is running
Bike is running safely
Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
super.run(); // invokes the super class method
System.out.println("Bike is running safely");
}
obj.run();
}
}
Output:
Vehicle is running
Bike is running safely
56
Method Overloading Method Overriding
Parameter must be different and Both name and parameter must be same.
name must be same.
Access specifier can be changed. Access specifier most not be more restrictive than
original method (can be less restrictive).
Abstract class:
Abstraction in Java
Another way, it shows only important things to the user and hides the internal details.
1. Abstract class
2. Interface
• Abstract classes may or may not contain abstract methods, i.e., methods without body (
public void get(); )
• But, if a class has at least one abstract method, then the class must be declared
abstract.
• place the abstract keyword before the method name in the method declaration.
• Instead of curly braces, an abstract method will have a semoi colon (;) at the end.
final keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
58
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
If variable is final, then the value of final variable cannot be changed (It will be
constant).
There is a final variable speedlimit, while trying to change the value of this variable, it
can't be changed because final variable once assigned a value can never be changed.
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400; //compile time error ;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
Java final method
60