Unit-1 Java
Unit-1 Java
What is OOP?
Objet Oriented Programming is software design method that models the characteristics of abstract or real
objects using classes and objects.
A class is a set of objects with similar properties (attributes), common behaviour (operations), and
common link to other objects.
The objects are variable of type class. A class is a collection of objects of similar type. Classes are
user defined data types and work like the build in type of the programming language.
2. Data Abstraction and Encapsulation
Data abstraction refers to the act of representing important description without including
thebackground details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, cost and functions operate on these attributes. They summarize all the important properties of
the objects that are to be created.
Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT).
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It ismost
useful feature of class. The data is not easy to get to the outside world and only those functions which are
enclosed in the class can access it.
These functions provide the boundary between Object‘s data and program. This insulation of data
from direct access by the program is called as Data hiding.
3. Inheritance
Inheritance is the process by which objects of one class can get the properties of objects of another
class.
Inheritance means one class of objects inherits the data and behaviours from another class. Inheritance
maintains the hierarchical classification in which a class inherits from its parents.
4. Polymorphism
5. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code related with a given procedure call is not known until the time of the
call at run time.
Dynamic binding is associated polymorphism and inheritance.
6. Message Passing
Basics of JAVA
History of JAVA
1. Compiled and Interpreted: Basically a computer language is either compiled or interpreted. Java
comes together both these approach thus making Java a two-stage system.
Java compiler translates Java code to Bytecode instructions and Java Interpreter generate machine
code that can be directly executed by machine that is running the Java program.
2. Platform Independent and portable: Java supports the feature portability. Java programs can be
easily moved from one computer system to another and anywhere. Changes and upgrades in operating systems,
processors and system resources will not force any alteration in Java programs.
Java certifies portability in two ways.
First way is, Java compiler generates the bytecode and that can be executed on any machine. Second
way is, size of primitive data types are machine independent.
4. Robust and secure: Java is a most strong language which provides many securities to make certain
reliable code. It is design as garbage –collected language, which helps the programmers virtually from all
memory management problems. Java also includes the concept of exception handling, which detain serious
errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use this
language for programming on Internet.
5. Distributed: Java is called as Distributed language for construct applications on networks which
can contribute both data and programs. Java applications can open and access remote objects onInternet
easily. That means multiple programmers at multiple remote locations to work together onsingle task.
6. Simple and small: Java is very small and simple language. Java does not use pointer and
header files, goto statements, etc. It eliminates operator overloading and multiple inheritance.
7. Multithreaded and Interactive: Multithreaded means managing multiple tasks simultaneously. Java
maintains multithreaded programs. That means we need not wait for the application to complete one task
before starting next task. This feature is helpful for graphic applications.
8. High performance: Java performance is very extraordinary for an interpreted language, majorly due to
the use of intermediate bytecode. Java architecture is also designed to reduce overheads during runtime. The
incorporation of multithreading improves the execution speed of program.
9. Dynamic and Extensible: Java is also dynamic language. Java is capable of dynamically linking in new
class, libraries, methods and objects. Java can also establish the type of class through the query building it
possible to either dynamically link or abort the program, depending on the reply.
Java program supports functions written in other language such as C and C++, known as native
methods.
Java Development kit (JDK) – The JDK comes with a set of tools that are used for developing and running Java
program.
It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javah(It is for java C header files)
6. Javadoc(It is for creating HTML document)
7. Jdb(It is Java debugger)
For compiling and running the program we have to use following commands:
b) java(Java Interpreter)
As we learn that, we can use any text editor for writing program and then save that program with
―.java extension. Java compiler converts the source code or program in bytecode and interpreter convert ―.java
file in ―.class file.
Syntax:
C:\java filename
If my filename is abc.java then the syntax will be
C:\java abc
Java Virtual machine(JVM) and Byte Code: As we know that all programming language compilers convert the
source code to machine code.Same job done by Java Compiler to run a Java program, but the difference is that Java
compiler convert the source code into Intermediate code is called as bytecode. This machine is called the Java
Virtual machine and it exists only inside the computer memory.
Documentation Section
1. Documentation Section: It comprises a set of Comment lines giving the name,the author and other details
of program, which the programmer would like to refer to at later stage.
2. Package Statement: It declares a package name and informs a compiler that the classes defined here belong
to this package.
package student;
3. Import Statement: It instructs the interpreter to load the classes contained in specific packages
import student.test;
4. Interface Statement: An interface is like a class but includes a group of method declarations.
5. Class Definitions: A java program may contain multiple class definitions which can be defined in this
section.
6. Main Method Class: Main method is starting point of a Java program and so there must be a class with
main method in every Java program.
A main method creates objects of various class and establishes communication between them.
class FirstProgram
{
public static void main(String args[])
{
System.out.println(―This is my first program );
}
}
Here,
z-public is an access specifier that declares the main method as unprotected and therefore making it
accessible to all other classes.
-static is keyword which can be called & executed without creating the object, so when we want to call
main() method without using an object we should declare a main() method as static.
-void means no value & as main() method doesn’t return any value, its return type is set to void.
-String args[] is array of String type which is used to store command line arguments.
Building Blocks
Tokens
There are five types of token as follows:
1. Literals
2. Identifiers
3. Keyword
4. Operators
5. Separators
1. Literals: Literals in Java are a sequence of characters (digits, letters and other characters) that
characterize constant values to be stored in variables. Java language specifies five major types of
literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
2. Identifiers: Identifiers are programmer-created tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following
rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.
3. Keywords: Keywords are important part of Java. Java language has reserved 50 words as keywords.
Keywords have specific meaning in Java. We cannot use them as variable, classes and method.
Following table shows keywords.
Boolean
abstract char catch
implements
default finally do
Private
If long throw
Double
package static break
protected
This volatile import
Else
class throws byte
Transient
float final public
Extends
native instanceof case
New
Int null const
Switch
return try for
synchronized
interface void while
Super
short continue goto
assert const
4. Operator: Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to
operate data and variables. They frequently form a part of mathematical or logical expressions.
Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
4.1 Arithmetic operators: Arithmetic operators are used to make mathematical expressions and the
working out as same in algebra. Java provides the fundamental arithmetic operators. These can
operate on built in data type of Java.
Multiplication
*
Modulo division or remainder
%
4.2 Logical operators: When we want to form compound conditions by combining two or more
relations, then we can use logical operators.
4.3 Relational Operators:When evaluation of two numbers is performed depending upon their
relation, assured decisions are made.
The value of relational expression is either true or false.
4.4 Assignment Operators: Assignment Operators is used to assign the value of an expression to a
variable and is also called as Shorthand operators.
Variable_name binary_operator = expression
4.5 Conditional Operators:The character pair ?: is a ternary operator of Java, which is used to
construct conditional expressions of the following form:
4.6 Increment and Decrement Operators: The increment operator ++ adds 1 to a variable. Usually
the variable is an integer type, but it can be a floating point type. The two plus signs must not be
split by any character. Usually they are written immediately next to the variable.
Following table shows the use of operators.
Expression Process Example end result
A++ Add 1 to a variable int A=10,B; A=11
after use. B=A++; B=10
++A Add 1 to a variable int A=10,B; A=11
before use. B=++A; B=11
A-- Subtract 1 from a int A=10,B; A=9
variable after use. B=A--; B=10
--A Subtract 1 from a int A=10,B; A=9
variable before use. B=--A; B=9
4.7 Bit Wise Operators: Bit wise operator execute single bit of their operands. Following table
shows bit wise operator:
Operator Importance/ significance
| Bitwise OR
& Bitwise AND
&= Bitwise AND assignment
|= Bitwise OR assignment
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
~ One‘slementcomp
5. Separator: Separators are symbols. It shows the separated code.they describe function of our code.
Name Use
() Parameter in method definition, containing statements for conditions,etc.
{} It is used for define a code for method and classes
[] It is used for declaration of array
; It is used to show the separate statement
, It is used to show the separation in identifier in variable declarartion
. It is used to show the separate package name from sub-packages and classes,
separate variable and method from reference variable.
- As with thee keyword class, Java data types are case sensitive.
Java Data
Types
Non
Numeric Classes Interface Arrays
Numeric
Floating
Integer Character Boolean
Point
Scope of Variables
An area of the program where the variable is accessible is called the scope of the variable.
Java Supports 3 types of variables:
1. Instance Variables
2. Class Variables
3. Local Variables
1. Instance Variables:
-These
These are declared in Class.
-They
They are created when the objects are instantiated and therefore they are associated with
objects.
-They
They carry different value for each object.
2. Class Variables:
-These
These are global to class and belong to entire set of objects that class created.
-Only
Only one memory location is created for each class variable.
3.Local Variables:
-These are declared and used methods and so they are not available to be used outside the method
where they were declared.
Command line arguments are parameters that are supplied to the application program at the time of invoking
its execution. They must be supplied at the time of its execution following the file name.In the main () method, the
args is confirmed as an array of string known as string objects. Any argument provided in the command line at the
time of program execution, are accepted to the array args as its elements. Using index or subscripted entry can access
the individual elements of an array. The number of element in the array args can be getting with the length
parameter.
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=”+c);
}
}
output:
c:\javac Add.java
c:\java Add 5 2
Control Statements
Selection Statements
1. if
if(Test condition)
{
Statement 1;
}
2. if-else
if (condition)
{
Statement 1;
Statement 2;
...
}
else
{
Statement 3;
Statement 4;
...
}
Example:
3. nested if-else
if (condition1)
{
if(condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
Example:
4. else if ladder
if(condition1)
{
Statement block1;
}
else if(condition2)
{
Statement block2;
}
else if (condition3)
{
Statement block3;
}
else if(condition 4)
{
Statement block4;
}
else
{
Statement block5;
}
Example:
5. switch statement
break;
…
default:statement block-default;break;
}
Example:
Iteration Statements
i.For loop
for(initialization;condition;iteration)//iteration means increment/decrement
{
Statement block;
}
ForExample.java
Output:
1
2
3
4
5
6
7
8
9
10
ii.While loop
While(condition)
{
Statement block;
}
WhileExample.java
Output:
1
2
3
4
5
6
7
8
9
10
DoWhileExample.java
1
2
3
4
5
6
7
8
9
10
Jumping Statements
1.break statement
When break statement is encountered inside the loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.
Syntax: break;
Example:
BreakExample.java
Output:
1
2
3
4
2.continue statement
continue statement tells the compiler that “Skip the following statements and continue with next
iteration of the loop.”
Syntax: continue;
ContinueExample.java