0% found this document useful (0 votes)
4 views

Java Programming (1)

This document provides an introduction to Java programming, detailing its features, object-oriented concepts, and basic syntax. It covers topics such as Java's platform independence, data types, operators, control statements, and the structure of Java programs. Additionally, it explains key concepts like objects, classes, inheritance, polymorphism, and the various types of tokens used in Java.

Uploaded by

nishanthp2806
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Programming (1)

This document provides an introduction to Java programming, detailing its features, object-oriented concepts, and basic syntax. It covers topics such as Java's platform independence, data types, operators, control statements, and the structure of Java programs. Additionally, it explains key concepts like objects, classes, inheritance, polymorphism, and the various types of tokens used in Java.

Uploaded by

nishanthp2806
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT -I

Name of the Paper : JAVA PROGRAMMING


Semester : II
Department : B.Sc Information Technology
Name of the Faculty : T.Ravishankar
Designation : Asst Professor
INTRODUCTION TO JAVA:

• Java is a general-purpose, object-oriented programming


language developed by Sun Microsystems of USA in
1991.Originally called Oak by James Gosling.
• A general-purpose programming language made for developers
to write once run anywhere that is compiled Java code can run
on all platforms that support Java.
• Java applications are compiled to byte code that can run on any
Java Virtual Machine (JVM).
• Java a really simple, reliable, portable and powerful language.
• Java is known as a platform-independent language.
• Java is the name of an island in Indonesia where the first coffee
(named java coffee) was produced.
• And this name was chosen by James Gosling while having coffee
near his office.
JAVA FEATURES:
Sun Microsystems officially describes Java with the following
attributes.
Compiled and Interpreted:
• Java compiler translates source code into what is known as bytecode
instructions.
• Java Interpreter generates machine code that can be directly executed
by the machine that is running the java program.
Platform-Independent and portable:
• Java program can be easily moved from one computer system to
another, anywhere and anytime.
• Java ensures portability in two ways.
• First java compiler generates bytecode instruction that can be
implemented on any machine.
• Secondly, the size of the primitive data types is machine-independent.
Object-Oriented:
• Java is a true object-oriented language. Always everything in java is an
object.
• All program code and data reside within objects and classes.
Robust and Secure:
• Java is a robust language.
• It provides many safeguards to ensure reliable code.
• Security becomes an important issue for a language that is used for
programming on internet.
• It also ensures that no viruses are communicated with an applet.
Distributed:
• Java is designed as a distributed language for creating application on
networks.
• It has the ability to share both data and programs.
Simple, Small and Familiar:
• Java is a small and simple language.
• Java does not use pointers, preprocessor header files, goto statement
and many others.
• It also eliminates operator overloading and multiple inheritance.
Multithreaded and Interactive:
• Multithreaded means handling multiple tasks simultaneously.
• 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
• 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 byte code.
Dynamic and Extensible:
• Java is a dynamic language.
• Java is capable of dynamically linking in new class libraries, methods and
objects.
• Java programs support functions written in other language such as C and
C++.These functions are known as native methods.
JDBC Row set:
• Java supports JDBC Row set (Java Database Connectivity) to send data in
a tabular format between the remote components of a distributed
enterprise application.
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
Objects and Classes:
• Objects are the basic runtime entities in an object-oriented system.
They may represent a person, a place, a bank account, a table of data or
any item that the program may handle. They may also represent
user-defined data types such as vectors and lists.
• A class is thus a collection of objects of similar type.
For example:
If fruit has been defined as a class, then the statement
Fruit mango
Will create an object mango belonging to the class fruit.

Data Abstraction and Encapsulation:


• The wrapping up of data and methods into a single unit is known as
encapsulation. The data is not accessible to the outside world and only
those methods, which are wrapped in the class, can access it.
• Abstraction refers to the act of representing essential features without
including the background details or explanations. For example: Mobile
Phone
Inheritance:
• Inheritance is the process by which objects of one class acquire the
properties of objects of another class.
• It supports the concepts of hierarchical classifications.
• There can be three types of inheritance in java: single, multilevel
and hierarchical.
For Example:

Bird
Attributes

Flying Bird Non-Flying Bird


Attributes Attributes
Polymorphism:
• Polymorphism means the ability to take more than one form. For Example:
Operation of Addition.
• The fig illustrates that a single function name can be used to handle different
number and different types of argument.

Compile time and Runtime Mechanisms:


• Compile time may refer to any of the following;
• The operations performed by the compiler such as syntactic and semantic
analysis.
• Runtime on the other hand, is the time period when a syntactically correct
program is actually executed in the computer system.
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 associated with a given
procedure call is not known until the time of the call at runtime.
Message Communication:
• Objects communicate with one another by sending and receiving
information much the same way as people pass message to one
another.
• Message passing involves specifying the name of the object, the
name of the method and the information to be sent. For Example
Employee.salary(name)

Object Information
Message
JAVA TOKENS
The smallest individual units in a program are known as tokens. Java language
includes five types of tokens. They are:
• Reserved Keywords
• Identifiers
• Literals
• Operators
• Separators.
Keywords
• Keywords are an essential part of a language definition. Java language has reserved
50 words as keywords. Some of them are
Abstract Boolean break
Byte case implements
Import extends package
Return super throw
Identifiers:
Identifiers are programmer-designed tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interface in a program. The rules:
• They can have alphabets, digits and the underscore, dollar sign.
• They must not begin with a digit.
• Uppercase an lowercase letters are distinct.
• They can be of any length.
Literals
Literals in java are a sequence of characters (digits, letters and other
characters) they represent constant values to be stored in variables. The five
major types of literals are
• Integer literals
• Floating point literals
• Character literals
• String literals
• Boolean literals
Operators:
An operator is a symbol that takes one or more arguments and operates on
them to produce a result.

Separators:
Separators are symbols used to indicate where groups of code are divided
and arranged. They basically define the shape and function of our code. Some of
the are
• Semicolon (;)
• Comma (,)
• Period (.)
• Braces ({})
JAVA STATEMENTS
A statement is an executable combination of tokens ending with a semicolon (;)
mark. Statements are usually executed in sequence in the order in which they appear.

STAETEMENT DESCRIPTION

Labelled Statement Any statement may begin with a label. Such labels must not be keywords etc

Expression Most statement are expression statements.Assignment,Pre-post-increment


,decrement

Selection statement These select one of several control flows. If-else and switch

Iteration Statement These specify how looping will take place.While,do and for

Jump Statement Jump statement pass control to the beginning or end of the current block.Break,
continue, return and throw.

Synchronization Statement These are used for handling issues with multithreading
CONSTANTS
Constants in java refer to fixed values that do not change during the
execution of a program. Java supports several types.
I. Integer constants:
An integer constant refers to a sequence of digits. There are three types of integer
Decimal Integer
It consists of a set of digits, 0 through 9.
Example: valid
123, -123, 0, 45673
Invalid
15 20.000 $1000
An octal integer constant consists of any combination of digits from the set 0
through 7, with a leading 0.
Example: valid
037 0 0435 0552
Invalid
45 1023
A sequence of digits preceded by 0x or 0X as Hexadecimal integer. They may
also include alphabets A through F or a through f.
Example: valid
0x2 0x9f0xbcd
Invalid: 09 f56
II ) Real Constants:
These quantities are represented by numbers containing fractional
partslike17.548.Such numbers are called real (or floating point) constants.
Example:
0.456 78.98 654.12

III) Single Character Constants:


Single character constant contains a single character enclosed within a pair of
single quote marks.
Example:
‘5’ ‘x’ ‘;’ ‘‘

IV) String Constants:


A string constant is a sequence of characters enclosed between double
quotes. The characters may be alphabets, digits, special characters and blank
spaces.
Example:
“Hello” “1998” “5+3” “x”
VARIABLES:
• A variable is an identifier that denotes a storage location used
to store a data value.
• A variable may take different values at different times during
the execution of the program.
• A variable name can be chosen by the programmer in a
meaningful way.
Some example are
Average, height, total_height, classstrength
• Variable names may consist of alphabets,digits,the
underscore(_) and dollar characters. The rules are
• They must not begin with a digit.
• Upercase and lowercase are distinct
• It should not be a keyword.
• White space is not allowed
• Variable names can be of any length.
DATA TYPES:
Data types specify the size and type of values that can be stored .Java
language is rich in its data types.
• Integer Types:
Integer types can hold whole numbers such as 123,-987 and 567.Java
supports four types of integer. They are byte, short, int and long

TYPE SIZE
Byte One Byte
Short Two Byte
Int Four Byte
Long Eight byte
• Floating Point Types
We use floating point type to hold numbers containing fractional parts such
as 27.59 and -89.34.
The float type values are single-precision numbers while the double types
represent double-precision numbers.
Character Type:
In order to store character constants in memory, java provides a character data type
called char. The char type assumes a size of 2 bytes but, basically, it can hold only a
single character.
Boolean Type:
The Boolean type is used when we want to test a particular condition during the
execution of the program. There are only two values that a Boolean type can take: true
or false.

TYPE CASTING:
Where there is a need to store a value of one type into a variable of another type. In such
situation, we must cast the value to be stored by preceding it with the type name in
parentheses. The syntax is:
Type variable1= (type) variable2;
The process of converting one data type to another is called casting. Examples
Int m = 50;
Byte n = (byte) m;
Longcount = (long) m;
OPERATORS:
Java operators can be classified into a number of
related categories as below.

• Arithmetic operators
• Relational operators
• Logical operators
• Assignment Operators
• Increment and Decrement operators
• Conditional Operators
• Bitwise operators
• Special operators
• Arithmetic Operators:
Arithmetic operators are used to construct mathematical expression
as in algebra. Java provides all the basic arithmetic operators. They are
listed below

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo division(Remainder)
i) Integer Arithmetic:
When both the operands in a single arithmetic expression such as a+b
are integer, the expression is called an integer expression, and the operation
is called integer arithmetic.

a-b=10
a+b=18

ii) Real Arithmetic:


An arithmetic operation involving only real operands is called real
arithmetic. A real operand may assume values either in decimal or
exponential notation.
a=20.5
b=6.5
a+b=28.8

iii) Mixed-mode Arithmetic:


When one of the operands is real and other is integer, the expression is
called a mixed-mode arithmetic expression.
15/10.0 produces the result 1.5
Relational Operators
We often compare two quantities, and depending on their relation, take
certain decisions. These comparisons can be done with the help of relational
operators.

Operator Meaning

< Is less than

<= Is less than or equal to

> Is greater than

>= Is greater than or equal to

== Is equal to

!= Is not equal to

Example:
A<b x>20
Logical Operators:
Java has three logical operators, which are given in table

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Example:
a>b &&x==10
An expression of this kind which combines two or more relational
expressions is termed as a logical expression or a compound relational
expression.
Assignment Operators:
This operator is used to assign the value of an expression to a variable. We
have seen the usual assignment operator,”=”.
V op=exp;
Where v is a variable, exp is an expression and op ia a java binary operator.
Example:
x=y+1; a=x+(y+2);

Increment and Decrement operators:


Java has two very useful operators not generally found in many other
languages. These are the increment and decrement operators.

++ and --
The operator ++ adds 1 to the operand while – subtracts 1.Both are unary
operators and are used in the following form
++m m++
--I i—
Conditional Operator:
The character pair? : is ternary operator available in java. This operator is used
to construct conditional expression of the form
Exp1? Exp2:exp3
Where exp1, exp2 and exp3 are expression.
Example:
X= (a>b)? a: b;
Bitwise Operators:
These operators are used for testing the bits or shifting them to the right or
left. Bitwise operators may not be applied to float or double.

Operator Meaning

& Bitwise AND

! Bitwise OR

^ Bitwise Exclusive OR

<< SHIFT LEFT

>> SHIFT RIGHT


Special Operator:
The dot operator(.) is used to access the instance variable and methods of
class objects.
Example
Person1.age
Person1.salary()

EXPRESSION
An arithmetic expression is a combination of variables,
constants and operators arranged as per the syntax of the
language.

A+b-c+14 a*b/c a*b/c


CONTROL STATEMENTS:
DECISION MAKING STATEMENT:

The if statement is a powerful decision making statement


and is used to control the flow of execution of staments.The types
are:

• Simple If stamen
• If… else statement
• Nested if…else statement
• Else if ladder
• Simple I f statement:

The general form of a simple if statement is


If (test expression)
{
Statement-block;
}
Statement-x;
• The statement-block may be a single statement or a group of statement.
• If the test expression is true, the statement-block will be executed; otherwise
the statement-block will be skipped and the execution will jump to the
statement-x.

Example:

If (category==sports)
{
marks=marks+bonus_marks;
}
System.out.println (marks);
………………………………………..
• The IF….ELSE statement
The general form is
If (test expression)
{
True-Statement-block;
}
Else
{
False-statement-block;
}
Statement-x;
If the test expression is true, then the true-statement-block immediately following the
if statements are executed; otherwise the false-statement-block are executed.
Example:
If(code==1)
{
Boy=boy+1;
}
Else
{
Girl=girl+1;
}
……………………………….
• NESTING OF IF…ELSE STATEMENT:
When a series of decisions are involved, we may have to use more than
one if…..else statement in nested form as follows.
Syntax:
If(test condition)
{
If(test condition)
{
Statement-1;
}
Else
{
Statement-2;
}
}
Else
{
Statement3;
}
Statement-x;
• If condition1 is false, the statment3 will be executed; otherwise it continues to
perform the second test.
• If the condition2 is true, the statement1 will be executed; otherwise the
statement2 will be evaluated and then the control is transferred to the
statement-x.
Example:
If(sex=female)
{
If(balance>10000)
{
Bonus=0.05*balance;
}
Else
{
Bonus=0.03*balance;
}
}
Else
{
Bonus=0.02*balance
}
Balance=balance+bonus;
• The Else If Ladder:
It takes the following general form as
If (condition 1)
Statement-1;
Else if (condition 2)
Statement-2;
Else if (condition 3)
Statement-3;
…………………………………
…………………………………
Else if (condition n)
Statement-n;
Else
Default-statement;
Statement-x;

• This construct is known as else if ladder.


• The conditions are evaluated from the top downwards.
• As soon as the true condition is found, the statement associated with it is executed and
the control is transferred to the statement-x.
• When all the n condition become false, then the final else containing the
default-statement will be executed.
Example:
if(mark>=70)
{
System.out.println("Distinction");
}
else if(mark>=60)
{
System.out.println("First Class");
}
else if(mark>=50)
{
System.out.println("Second Class");
}
else if(mark>=40)
{
System.out.println("Pass");
}
else
{
System.out.println("Failed");
}
SWITCH STATEMENT:
Java has a built-in multiway decision statement known as switch. The general
form of the switch statement is as shown below.

Switch (expression)
{
Case value-1:
Block-1;
Break;
Case value-1:
Block-1;
Break;
…………………
…………………
Default:
Default-Block;
Break;
}
Statement-x;
• The expression is an integer expression or characters.
• Value-1, value-2…..is constants or constant expression and is known as case
labels.
• Each of these values should be unique within a switch statement, block-1,
block-2… may contain zero or more statements.
• When the switch is executed the value of the expression is successively
compared against the values value-1, value-2…..
• If a case is found then the block of statement that follows the case are
executed.
• The break statement signals the end of a particular case.
• The default is an optional case. It will be executed if the value of the
expression does not match with any of the case values.
Example:
Switch(index)
{
Case 10:
Case 9:
Case 8:
Grade=”Honours”;
Break;
Case 7:
Case 6:
Grade=”First Class”;
Break;
Case 5:
Grade=”Second Class”;
Break;
Case 4:
Grade=”Third Class”;
Break;
Default:
Grade=”Fail”;
Break;
}
System.out.println("Your grade is " + Grade);
LOOPING STATEMENT

• The while statement


The basic format of the while statement is
Initialization:
While (test condition)
{
Body of the loop
}
• The while is an entry-controlled loop statement.
• The test condition is evaluated and if the condition is true, then the body of
the loop is executed.
• This process of repeated execution of the body continues until the test
condition finally becomes false and the control is transferred out of the loop.
• On exit, the program continues with the statement immediately after the body
of the loop.
Examples:
Sum=0;
N=1;
While (n<=10)
{
Sum=sum+n*n;
N=n+1;
}
System.out.println (“Sum=”+sum);

• The do while loop statement

This takes the form


Initialization:
Do
{
Body of the loop;
}
While (test condition);
• The do…while construct provides an exit-controlled loop.
• On reaching the do statement, the program proceeds to evaluate the body of
the loop first.
• At the end of the loop, the test condition in the while statement is evaluated.
• If the condition is true, the program continues to evaluate the body of the loop
once again.
• When the condition becomes false, the loop will be terminated.

Example:
I=1;
Sum=0;
Do
{
Sum=sum+I;
I=i+2;
} while (sum<40||s<10);
………………………………
……………………………..
• The for statement:
The for loop is another entry-controlled loop that provides a more concise
loop control structure. The general form is
For (initialization; test condition; incre/decr)
{
Body of the loop;
}
• Initialization of the control variables is done first, using assignment statements
such as i=1 and count=0.
• The test condition is a relational expression, such as i<10 that determines when
the loop will exit.
• If the condition is true, the body of the loop is executed; otherwise the loop is
terminated.
• The control variable is incremented using an assignment statement such as
i=i+1;
• This process continues till the value of the control variable fails to satisfy the
test condition.
Example:
for(x=0; x<=9; x++)
{
System.out.println(x);
}

You might also like