Java 1
Java 1
1.0 Introduction to Object OrientedProgramming Most function uses Global datafor Data cannot move easily from function
The 1960s gave birth to structured programming. This is the method of programming sharing that can be accessed freely to function, it can be kept public or
Data Access
championed by languages such as C. With the advent of languages such as c, structured from function to function inthe private so we can control the access of
programming became very popular and was the main technique of the 1980‟s. Structured system. data.
It does not have any proper way for It supports data hiding so provides
programming was a powerful tool that enabled programmers to write moderately complex Data Hiding hiding data so it is less secure. more security.
programs fairly easily. However, as the programs grew larger, even the structured approach In OOP, overloading is possible in the
failed to show the desired result in terms of bug-free, easy-to- maintain, and reusable programs. Overloading In POP, Overloading is not possible. form of Function Overloading and
To solve these problems, a new way to program was invented, called object-oriented Operator Overloading.
programming(OOP). Inheritance No such concept of inheritance in POP Inheritance is allowed in OOP
Access It has access specifiers named Public,
It does not have any access specifiers.
Object Oriented Programming (OOP) is an approach to program organization and Specifiers Private, Protected.
development that attempts to eliminate some of the pitfalls of conventional programming C, BASIC, FORTRAN, Pascal, C++, JAVA, C#, Smalltalk, Action
Examples COBOL. Script.
methods by incorporating the best of structured programming features with several powerful new
concepts. It is a new way of organizing and developing programs and has nothing to do with any
1.2 Principles ofOOP
particular language. However, not all languages are suitable to implement the OOP concepts It is necessary to understand some of the concepts used extensively in object-oriented
easily. programming. Theseinclude:
Object Inheritance
1.1 PO Programming Vs OOProgramming Class Polymorphism
All computer programs consist of two elements: code and data. Furthermore, a program Encapsulation Dynamicbinding
can be conceptually organized around its code or around its data. That is, some programs are Dataabstraction Messagepassing
written around ― “what is happening” and others are written around ―“who is being affected”.
These are the two paradigms that govern how a program is constructed. The first way is called Object
Object is the basic run time entity in an object-oriented system. It may represent a person,
the process- oriented model or procedural language. This approach characterizes a program as a
a place, a bank account, a table of data, vectors, time and lists. Objects have states and behaviors.
series of linear steps (i.e. code). The process-oriented model can be thought of as code acting on Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking,
data. Procedural languages such as C employ this model to considerablesuccess. eating. An object is an instance of a class.
To manage increasing complexity, the second approach, called object-oriented In OOP, A problem is analyzed in term of objects and the nature of communication
programming, was designed. Object-oriented programming organizes a program around its data between them. Objects should be chosen such that they match closely with the real-world
(i.e. objects) and a set of well-defined interfaces to that data. An object-oriented program can be objects.Objectstakeupspaceinthememoryandhaveanassociatedaddresslikeastructurein
C. When a program is executed, the objects interact by sending messages to oneanother.
characterized as data controlling access to code.
For example, if “customer” and “account” are to object in a program, then the customer
Difference between POP and OOP object may send a message to the account object requesting for the bank balance. Each object
Procedure Oriented Programming Object Oriented Programming contain data, and code to manipulate data. Below figure shows two notations that are popularly
Program is divided into small parts Program is divided into parts used in object oriented analysis and design.
Divided Into
called functions. called objects.
Importance is given to the data rather
Importance is given to functions as
Importance than procedures or functions because it
well as sequence of actions to be done.
works as a real world.
Approach It follows Top-down approach. It follows Bottom-up approach.
Data Data can move freely from function to Objects can communicate with each
Moving function in the system. other through member functions.
To add new data and function in POP It provides an easy way to add new data
Expansion
is not so easy. and function.
Encapsulation
Definition: The process binding (or wrapping) code and data together into a single unit is known
as Encapsulation. For example: capsule, it is wrapped with different medicines.
Inheritance
It a process by which an object of one class acquires the properties and methods of
another class. It supports the concept of hierarchical classification. For example, the bird,
„robin‟ is a part of class „flying bird‟ which is again a part of the class „bird‟. The principal
behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived as illustrated in belowfigure.
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by deriving Advantages of OOP
a new class from the existing one. The new class will have the combined feature of both the OOP offers several benefits to both the program designer and the user. Object-Orientation
classes. The Class from which the properties are acquired is called super class, and the class that contributes to the solution of many problems associated with the development and quality of
James Gosling Five Goals which were taken into consideration while developing Java
1. Keep it simple, familiar and objectoriented.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. 2. Keep it Robust andSecure.
There are given the major points that describe the history of java. 3. Keep it architecture-neural andportable.
4. Executable with HighPerformance.
1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language 5. Interpreted, threaded anddynamic.
project in June 1991 at Sun Microsystems. The small team of sun engineers called Green
Team. Why we call it Java 2, Java 5, Java 6, Java 7 and Java 8, not their actual version numbers
2. Originally designed for small, embedded systems in electronic appliances like set-top which 1.2, 1.5, 1.6, 1.7 and 1.8?
boxes. Java 1.0 and 1.1 were Java. When Java 1.2 was released it had a lots of changes and marketers /
3. Firstly, it was called "Greentalk" by James Gosling and file extension was“.gt”. developers wanted a new name so they called it Java 2 (J2SE), remove the numeric before
4. After that, it was called Oak and was developed as a part of the Greenproject. decimal. This was not the condition when Java 1.3 and Java 1.4 were released hence they were
5. Why Oak? Oak is a symbol of strength and chosen as a national tree of manycountries never called Java 3 and Java 4, but they were still Java 2.
like U.S.A., France, Germany, Romaniaetc.
6. In 1995, Oak was renamed as "Java" because it was already a trademark byOak When Java 5 was released, once again it was having a lots of changes for the developer /
Technologies. marketers and need a new name. The next number in sequence was 3, but calling Java 1.5 as
Why "Java" name Java 3 was confusing hence a decision was made to keep the naming as per version number and
7. Why had they chosen Java name for java language? The team gathered to choose a new till now the legacycontinues.
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA"etc.
They wanted something that reflected the essence of the technology: revolutionary, 1.4 Java Features / Buzzwords
dynamic, lively, cool, unique, and easy to spell and fun tosay. There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
According to James Gosling "Java was one of the top choices along with Silk". Since
java was so unique, most of the team members preferred Java. 1. Simple
8. Java is an island of Indonesia where first coffee was produced (called javacoffee). 2. Secure
9. Notice that Java is just a name not anacronym. 3. Portable
10. Originally developed by James Gosling at Sun Microsystems (which is now asubsidiary 4. Object-oriented
of Oracle Corporation) and released in1995. 5. Robust
11. In 1995, Time magazine called Java one of the Ten Best Products of1995. 6. Multithreaded
12. JDK 1.0 released in(January 23,1996). 7. Architecture-neutral
Java Version History 8. Interpreted
There are many java versions that have been released. Current stable release of Java is Java SE 8. 9. Highperformance
1. JDK Alpha and Beta(1995) 10. Distributed
2. Initial Java Versions 1.0 and 1.1 were released in the year 1996 for Linux, Solaris,Mac 11. Dynamic
and Windows.
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you
to write programs that do many thingssimultaneously.
Architecture-neutral
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was ― write once; run anywhere,
anytime, forever. To a great extent, this goal was accomplished.
2. Class(Method)Area
Class (Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.
Fourth line contains the "{", which is the beginning of the main function. Separators
Fifth line contains the statement In Java, there are a few characters that are used as separators. The separators are shown in the
System.out.println("Hello World"); following table:
Symbol Name Purpose
Here "System" is the predefined class, that provides access to the system, and out is the output () Parentheses Used to contain lists of parameters in method definition and
stream that is used to connect to the console. The println(), is used to display string passed to invocation. Also used for defining precedence inexpressions,
expressions in control statements, and surrounding casttypes.
it. This can even display other information to.
{} Braces Used to contain the values of automatically initialized arrays.
Used to define a block of code, for classes, methods, and local
1.7 Lexicalissues scopes
Java programs are a collection of whitespace, identifiers, literals, comments, operators, [] Brackets Used to declare array types and to dereferencing array values.
separators, and keywords. ; Semicolon Terminates statements.
, Comma Separates consecutive identifiers in a variable declaration.
Whitespace . Period Used to separate package names from sub-packages and classes
and used to separate a variable or method from a reference
Java is a free-form language. This means that you do not need to follow any special
variable.
indentation rules. For example, the Java program could be written all on one line or in any
other strange way you felt like typing it, as long as there was at least one whitespace
The Java Keywords
character between each token that was not already delineated by an operator or separator. In
There are 50 keywords currently defined in the Java language (see below Table).
Java, whitespace is a space, tab, ornewline.
These keywords, combined with the syntax of the operators and separators, form the
foundation of the Javalanguage.
Identifiers
These keywords cannot be used as identifiers. Thus, they cannot be used as names for
Identifiers are used to name things, such as classes, variables, and methods. An identifier may
a variable, class, ormethod.
be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore
The keywords const and goto are reserved but notused.
and dollar-sign characters. They must not begin with a number. Java is case-sensitive, so
In addition to the keywords, Java reserves the following: true, false, and null. These
VALUE is a different identifier than Value. Some examples of valid identifiers are
are values defined byJava.
1.9 Identifiers
Declaring a Variable
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
In Java, all variables must be declared before they can be used. The basic form of a variable
dollar-sign characters. They must not begin with a number, lets they be confused with a
declaration is shown here:
numeric literal. Java is case-sensitive, so VALUE is a different identifier than Value. Some
type identifier [ = value/literal][, identifier [= value/literal] ...] ; examples of valid identifiers are:
Here the type is any primitive data type, or class name. The identifier is the name of the
variable. We can initialize the variable by specifying the equal sign and value. Rules for Naming Identifier:
Example 1. The first character of an identifier must be a letter, or dollar($)sign.
int a,b,c; // declares three ints, a, b, andc. 2. The subsequent characters can be letters, an underscore, dollar sign ordigit.
int d = 3, e, f=5; // declares three more ints, initializing d and f. 3. White spaces are not allowed withinidentifiers.
byte z=22; // initializes z with22. 4. Identifiers are case sensitive so VALUE is a different identifier thanValue
double pi =3.1415; // declares an approximation of pi.
char c= 'x'; // variable c has the value'x' Valid Identifiers are as follows:
Average Temperature A1 Total_Score
Dynamic Initialization of the variable
We can also assign a value to the variable dynamically as follow: Invalid Identifiers are as follows:
int x = 12, y=13; 2a Area-circle Not/ok
float z = Math.sqrt (x+y);
Naming Convention for Identifiers
The Scope and Lifetime of Variables Class or Interface - These begin with a capital letter. The first alphabet of every
A scope determines what objects are visible to parts of your program. It also internal word is capitalized. Ex: classMyclass
determines the life time of theobjects. Variable or Method – These start with lower case letters. The first alphabet of every
Java allows, declaring a variable within anyblock. internal word is capitalized. Ex: inttotalPay;
Example program to perform all the arithmetic operations (Arith.java ) Arithmetic Compound Assignment Operators
import java.io.*; Java provides special operators that can be used to combine an arithmetic operation with an
class Arith assignment. As you probably know, statements like the following are quite common in
{ programming:
public static void main(String args[]) a = a + 4;
{ In Java, you can rewrite this statement as shown here: a += 4;
int a,b; This version uses the += compound assignment operator. Both statements perform the same
a=5; action: they increase the value of a by 4.
b=6;
intc=a+b; //arithmeticaddition Here is another example, a = a % 2; which can be expressed as a %= 2;
int d=a-b; //aritmeticsubtraction
inte=a/b; //arithmeticdivision Increment and Decrement Operators
intf=a*b; //arithmetic multiplication The ++ and the – – are Java‟s increment and decrementoperators.
System.out.println("The Sum is :"+c); The increment operator is unary operator that increases value of its operand by1.
System.out.println("The Subtraction is :"+d); Similarly, the decrement operator decreases value of its operand by1.
System.out.println("The Division is :"+e); These operators are unique in that they work only on variables not onconstants.
These are used in loops like while, do-while and forstatements.
System.out.println("The Multiplication is:"+f);
} There are two ways to use increment or decrement operators in expressions. If you put the
} operator in front of the operand (prefix), it returns the new value of the operand (incremented or
Output decremented). If you put the operator after the operand (postfix), it returns the original value of
The Sum is : -1 the operand (before the increment ordecrement)
The Subtraction is : -1 For example, this statement:
The Division is : 0 x = x + 1;
The Multiplication is : 30 can be rewritten like this by use of the increment operator: x++;
Operator Name Value returned Effect on variable
The Modulus Operator ( % ) x++ Post-increment x Incremented
The modulus operator returns the remainder of a division operation. It can be applied to ++x Pre-increment x+1 Incremented
integer types as well as floating-point types. The following program demonstrates the % x-- Post-decrement x Decremented
operator. --x Pre-decrement x+1 Decremented
Left-shift is equals to multiplication by 2. Java has six relational operators. The following table shows these operators along with their
The Right Shift( >> ) meanings
When we apply right-shift, every bit in x is shifted to right by one place. So, the LSB (Least Operator Meaning Example
Significant Bit) of x is lost, the MSB (Most Significant Bit) of x is set to previous value. This < Less than 4<5 return true
preserves the sign of the value. > Greater than 4>5 return false
<= Less than or equal to 100<=100 return true
>= Greater than or equal to 50>=100 return false
Let us considerintx=4; Now shifting the bits towards right for 1 time, will give the = =+ Equal to 4==5 return false
followingresult. != Not equal to 4!=5 return true
The following program demonstrates the Relational operators:
MVR@Dept. Of CSE 27 MVR@Dept. Of CSE 28
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
Example: ( RelOp.java ) The ? Operator
class RelOp Java includes a special ternary (three-way) operator that can replace certain types of if-then-
{ else statements. The ? has this general form:
public static void main(String args[])
{ var = expr1 ? expr2 : expr3
int x = 4,y=5; Here, expr1 can be any expression that evaluates to a boolean value. If expr1 is true, then
System.out.println(x + "<" + y +" = " + (x<y)); expr2 is evaluated; otherwise, expr3 is evaluated and its value is assigned to var.
System.out.println(x + ">" + y +" = " + (x>y));
System.out.println(x + "<=" + y +" = " + (x<=y)); The following program demonstrates the Relational operators: ( Ternary.java )
System.out.println(x + ">=" + y +" = " + (x>=y)); class Ternary
System.out.println(x + "==" + y +" = " + (x==y));
{
System.out.println(x + "!=" + y +" = " + (x!=y));
public static void main(String args[])
}
{
}
int x=4,y=6;
Output
int res= (x>y)?x:y;
4<5 = true
System.out.println("The result is :"+res);
4>5 = false
4<=5 = true }
4>=5 =false }
4==5 =false Output
4!=5 = true The result is : 6
Example Iteration: After completion of initialization and condition steps loop body code is executed
Write a java program to add all the number from 1 to 10. (using do-while) and then increment or decrements steps is execute. This statement allows to us to update any
classTest loop controlvariables.
{
public static void main(String[] args) How for loopworks?
{ First the loop initialization statement isexecuted.
int n=1; Then, the test expression is evaluated. If the test expression is false, for loop is
do terminated. But if the test expression is true, codes inside the body of for loop is
{ executed and the update expression is executed. This process repeats until the test
System.out.print(n+" "); expression becomesfalse.
n++;
} while (n<=10); Note: In for loop everything is optional but mandatory to place two semicolons (; ;)
} Example program: same program using the for loop
} class Test
Output: {
1 2 3 4 5 6 7 8 9 10 public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i+"");
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
Output
The sum is 7
After computing the result the control is transferred to the caller method, that main in this
case.