Unit 1
Unit 1
Unit 1
Class
Class is design time entity that consists of data and member function.
Class is a collection of objects of similar type.
Object
Object is basic run time entity that consists of data and member function.
It is variable of class type.
Data Encapsulation
Binding of data and methods into single unit (called class) is known as encapsulation.
Insulation of the direct access by program is called data hiding.
Data Abstraction
The act of representing essential features without including background details or
explanations is called data abstraction.
Inheritance
It is the process by which object of one class acquire properties of another class.
Polymorphism
It means ability to take more than one form. There are two types of polymorphism.
(1) Compile time polymorphism
(2) Run time polymorphism
Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
Static binding means code associated with given procedure call is not known until the time
of call at compile time.
Dynamic binding means code associated with given procedure call is not known until the
time of call at runtime.
Java is an object-oriented programming language which was developed by Sun Microsystems in.
Java programs are platform independant which means they can be run on any operating system
with any type of processor as long as the Java interpreter is available on that system. Java is a
case sensitive language.
History of Java:-
Java was developed by James gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems Inc. in 1991. Initial name of this language was “Oak” but it
was renamed in 1995 as “Java”.
Java is a powerful programming language. It is easy to learn for whom already familiar
with C or C++.
Through inheritance, we can eliminate redundant code and extend use of classes.
Its garbage collection helps you to reuse memory and also you can reuse people’s tested
code with fewer bugs.
In java, development time may be as much as twice faster that C++ Programs.
Features of data hiding and absence of pointer make program more secure.
You can update applets easily from a central server. New classes to be loaded without
recompiling entire program.
Simple
Java is a small and simple language. Many features of C and C + + that are either redundant
or sources of unreliable code are not part of Java.
For example, Java does not use pointers, preprocessor header files, goto statement and many
others. Java is a simplified version of C++. Java is simple for development.
Platform Independent
Platform independence means that a program can run on any computer system. Java
programs can run on any system for which a Java virtual machine has been installed.
Platform independence at the source level means that you can move Java source files from
system to system and have them compile and run on any system.
Platform independence in Java doesn't stop at the source level, however. Java compiled
binary files are also platform independent and can run on multiple platforms (if they have a
Java virtual machine available) without the need to recompile the source.
Portable
The most significant and important difference between java and other languages is its
portability.
Java programs can be easily moved from one computer system to other.
Changes and upgrades in OS, processor and system resources will not force any change in
java program.
Java ensures portability in two ways
->First, java compiler generates byte code instructions that can be implemented on any
machine.
->Secondly, the size of primitive data types is machine independent.
Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs.
Java applications can open and access remote objects on Internet as easily as they can do in
a local system. This enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
Multithreaded
Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs. This means that we need not wait for the application to finish one task before
beginning another.
For example, we can listen to an audio clip while scrolling a page and at the same time
download an applet from a distant computer. This feature greatly improves the interactive
performance of graphical applications.
The Java runtime comes with tools that support multiprocess synchronization and
construct smoothly running interactive systems.
High Performance
Java performance is impressive for an interpreted language mainly due to the use of
intermediate bytecode. According to Sun, Java speed is comparable to the native C/C + +,
Java architecture is also designed to reduce overheads during runtime. Further, the
incorporation of multithreading enhances the overall execution speed of Java programs.
Dynamic
Java is a dynamic language. Java is capable of dynamically linking in new class libraries,
methods, and objects. Java can also determine the type of class through a query, making it
possible to either dynamically link or abort the program, depending on the response.
Java programs support functions written in other languages such as C and C + +.
These functions are known as native methods. This facility enables the programmers to use
the efficient functions available in this language. Native methods are linked dynamically at
runtime.
Object-Oriented
Java is a true object-oriented language. Almost everything in Java is an object. All program
code and data reside within objects and classes. Java comes with an extensive set of classes,
arranged in packages that we can use in our programs by inheritance. The object model in
Java is simple and easy to extend.
SR JAVA C
NO
1 Java is object-oriented language. C is procedure oriented language.
2 Java does not support structure, union, C supports structure, union enum.
enum.
3 Java does not support Pointer. C supports pointer.
4 Java does not support Global variable C supports Global variable
5 Java does not support goto, sizeof, C supports goto, sizeof, typedef.
typedef.
6 There are no header files In java There is no. of header files In C.
7 Java does not support Pre-processor. C support Pre-processor.
8 Java doesn’t define type modifiers like C defines type modifiers keyword
auto, extern, register, signed, unsigned. Auto, extern, register, signed, unsigned.
SR JAVA C++
NO
1 Java does not support Operator C++ supports Operator overloading.
overloading.
2 Java does not support Template class. C++ support Template class.
3 Java does not support Multiple C++ supports Multiple inheritance.
Inheritance but it supports interface.
4 Java does not support Global variable C++ support Global variable
5 Java does not use Pointer. C++ use Pointer.
6 There are no header files in java There is no. of header files In C++.
7 Java has replace destructor Function C++ has a constructor & also
with finalize ( ). Destructor Function.
8 It does not support Pre-processor. C++ support Pre-processor.
The output of a Java compiler is bytecode not the machine code (“.class” file). Bytecode is a
highly optimized set of instructions designed to be executed by the Java run-time system, which
is called as JVM (Java Virtual Machine). JVM is the interpreter which interprets the bytecode.
JVM is an abstract computing machine like any other real computing machine which interpretes
the byte code (.class file which contains virtual machine instructions) to a machine dependent
native code. The output of JVM is the native code contains low level instructions which are
easily understandable by the micro processors which process the native code to give the desire
output.
A Java Virtual Machine (JVM) is a set of computer software programs and data structures which
use a virtual machine model for the execution of other computer programs and scripts.
The JVM runtime executes .class or .jar files, emulating the JVM instruction set by interpreting
it, or using a just-in-time compiler (JIT) such as Sun's Hotspot. JIT compiling, not interpreting, is
used in most Jams today to achieve greater speed. Like most virtual machines, the Java Virtual
Machine has a stack-based architecture.
Java environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development Kit (JDK)
and the classes and methods are part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).
They can also use a Java-enabled browser to download an applet on a computer anywhere in the
Internet and run it on his local computer (see fig.)
In fact, Java applets have made the Internet a true extension of the storage system of the local
computer.
Internet users can also set up their Web sites containing Java applets that could be used by other
remote users of Internet.
The ability to hitch a ride on the Information Superhighway has made Java a unique
programming language for the Internet. In fact, due to this, Java is popularly known as Internet
language.
Documentation Section
The documentation section comprises a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to refer to at a later
stage. We use comment for documentation.
Package Statement
The first statement allowed in a Java file is a package statement. This statement declares a
package name and informs the compiler that the classes defined here belong to this package.
The package statement is optional. That is, our classes do not have to be part of a package.
Import Statements
The next thing after a package statement (but before any class definitions) may be a number
of import statements. This is similar to the# include statement in c.
Interface Statement
An interface is like a class but includes a group of method declarations. It is new concept in
java. This is also an optional section and is used only when we wish to implement the
multiple inheritance features in the program.
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elements of a Java program. These classes are used to map the objects of real-world
problems. The number of classes used depends on the complexity of the problem.
Example:
// First.java
class First
{
public static void main ( String arg [ ] )
{
System.out.println (“Simple Java Program”);
}
}
Public: main ( ) is the first method called by java environment when a program is executed so it
has to accessible from java environment. Hence the access specifies has to be public.
Static: Java environment should be able to call this method without creating an instance of the
class, so this method must be declared as static.
Void: main function does not return anything so the return type must be void.
The argument String indicates the argument type which is given at the command line and args is
an array for string given during command line.
If a language supports pointers, then it gives the programmer the ability to reference any part of
the program's memory. This means that a program can reference variables, and read and write
them freely, by passing any kind of type safety or memory management.
Some kinds of programming need the ultimate flexibility of pointer. For example, low-level
device drivers need to access memory directly. Most programs do not need that much power,
and the risks imposed by pointers are very serious.
In Java all inside the class which not essentially requires pointer mechanism and by using
pointers we directly access the memory of the system, which cause some security problems and
JAVA doesn't allow it because everything should be under JVM. Another Fact is pointers are not
platform independent
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
Division(Remainder)
Example:
class Arith{
public static void main(String args[]) {
float no1, no2;
no1=17;
no2=02;
2. Relational Operators
As the name clear illustrates the meaning, the relational operators show the relations between
the two variables.
Relational Operators are –
Operator Meaning
> Greater Than
< Less Than
>= Greater Than Equal To
<= Less Than Equal To
== Equal To
!= Not Equal To
Example:
a<b True
a less than b?
a <= b True
a less than or equal to b?
a>b False
a greater than b?
a<b True
a less than b?
a >= b False
a greater than or equal to b?
a==c True
a equal to c
a!=b True
a not equal to b
3. Logical Operator
Logical operators are generally used with conditional statements and are used to combine
two conditions.
The three Logical Operators---
Example:
4. Assignment Operator
A compound assignment operator has the following syntax:
<variable> <op> = <expression>
Here <op>= can be any of the compound assignment operators. The compound assignment
operators have the lowest precedence of all the operators in Java, allowing the expression on
the right-hand side to be evaluated before the assignment. The following Table defines the
arithmetic compound assignment operators.
Increment Operator ++
In Prefix increment operator first it will increment the value of variable and then assign.
a = 2;
In Postfix increment operator first it will assign the value to the variable and then increment.
a = 5;
Decrement Operator –
In Prefix decrement operator first it will decrement the value of variable and then assign.
a = 2;
In Postfix decrement it operator first it will assign the value to the variable and then
decrement.
a = 5;
6. Conditional Operator
The character pair ?: is a ternary operator available in java.
Expression exp1 is evaluated first. If exp1 is true the exp2 is evaluated and if it is false then
exp3 is evaluated. In this only one of the expression is evaluated not both. It is equivalent to
if else statement.
a = 10, b = 15;
x = (a>b) ? a : b; ( output: x=15)
7. Bitwise Operator
The Bitwise operator when used with any operand works at its individual bits. It does not
work with float and double data type.
One’s complement
~a
Shift right with zero fill shift bits of a right by distance b (unsigned)
a >>> b
8. Special Operator
Java support some special operators such as instanceof operator and member selection
operator (.).
Instanceof operator
The instanceof is an object reference operator and returns true if the object on left hand side
is an instance of the class given on the right hand side.
Dot operator
The Dot operator (.) is used to access the instance variables and methods of class objects.
person . age // reference to the variable age
person . salary() // reference to the method salary()
It is also used to access classes and sub packages from a package.
The situations where there is a need to store a value of one type into a variable of another type.
In such situations, we must cast the values to be stored by preceding it with the type name in
parentheses.
Example:
int a = 20;
byte b = (byte) a;
long c = (long) a;
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double
Converting from a higher data type to a lower data type is called a narrowing primitive
conversion, which can result in loss of information. For example, a double can be converted
to an int with loss of information
Widening and narrowing conversions are also defined for reference types.
Example:
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
}
}
output:
JAVA LANGUAGE
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
statement 2 sequence;
braek;
case 3:
statement 3 sequence;
break;
--
--
--
--
case n:
break;
default :
default statement sequence;
}
Example: Program to find max of two numbers (Max.Java)
class Max
{
public static void main(String args[])
{
int a,b,max;
a = 10;
b = 20;
if(a>b)
max = a;
else
max = b;
System.out.println(“Max of two numbers is “ + max); //Output
}
}
Output:
Max of two numbers is 20
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control pass to the next
line of code immediately following the loop.
While and for loop are called entry controlled loop in which condition is checked first before
executing body of the loop. Do while loop is called exit controlled loop in which body of the
loop executed at least once before checking condition.
Example:
class Loop1{
public static void main(String args[]){
int n=5;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++)
System.out.print(j);
System.out.println();
}
}
}
Output:
1
12
123
1234
12345
3. Jump Statements
It allows our program to work in a non-linear fashion.
a. break
b. labeled break
c. continue
d. labeled continue
e. return
The conditional expressions used in the if, for, while and do statements
must be valid boolean expressions i.e. their values should be either true or false. We
cannot use 0 instead of false or a non-zero value instead of true.
The break statement is used to terminate the current block in which the
break statement is written. The break statement can be used to terminate a block like
selection and iteration statements.
The labeled break statement is used to terminate the block whose label is
specified in the break statement. Unlike simple break statement, we can terminate any
block. For example, it is possible to terminate the outermost loop from inside a deeply
nested for loop. The break statement can also be used to terminate a simple block (i.e.
the block need not be a loop or switch statement)
The continue statement causes the loop to be continued with the next
iteration after skipping any statements in between.
The labeled continue statement specifies the label of the enclosing loop
to continue. The label need not correspond to the closest enclosing loop.
The return statement is used in the function to return the value to the
calling function. It returns only one value at time.
Jump Statement:-
(a) break
for (int i=1;i<=10;i++)
{
if(i == 5)
break; //terminate loop if i is 5
System.out.print( i );
}
Output: 1234
(c) continue
for(int i=0;i<10;i++)
{
System.out.print( i + “ “);
if ( i % 2 = = 0 )
continue;
System.out.println();
}
Note:- This code use the % operator to check if i is even. if it is even then the loop will
continue without printing a new line.
Output:
0 1
2 3
4 5
6 7
8 9
(e) return
int sum(int a, int b)
{
int c;
c = a+b;
return(c);
}