Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Java 1

The document discusses an overview of Java programming including its history, development, key features and concepts like object-oriented programming. It describes objects, classes, encapsulation, inheritance and polymorphism as fundamental concepts of OOP used in Java.

Uploaded by

Sugavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java 1

The document discusses an overview of Java programming including its history, development, key features and concepts like object-oriented programming. It describes objects, classes, encapsulation, inheritance and polymorphism as fundamental concepts of OOP used in Java.

Uploaded by

Sugavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

PROGRAMMING IN JAVA

UNIT-I

AN OVERVIEW OF JAVA:

 James Gosling, Patrick Naughton, Chris Worth, ED Frank and Mike Sheridan
conceived Java at Sun Microsystems, Inc in 1991.
 It took 18 months to develop the first Working version. This language was initially
called „OAK‟ but was renamed “JAVA” in 1995.
 The primary motivation was the need for a platform-independent (i.e.
architecture-neutral) language that could be used to create software to be
embedded in various consumer electronic devices such as microwave oven and
remote controls.
 As you can probably guess, many different types of CPU‟s are used as controllers.
The trouble with C and C++ (and most other languages) is that they are designed
to be compiled for a specific target.
 Although it is possible to compile a C++ program for just about any type of CPU,
to do so requires a full C++ compiler together for that CPU.
 The problems are that compilers are expensive and time consuming to create. An
easier- more cost efficient solution was needed.
 In an attempt to find such a solution, Gosling and others began work on a
portable, platform-independent language that could be used to produce code that
would run on a variety of CPU‟s under different environments.
 This effort ultimately led to the creation of Java.
 In 1993, the World Wide Web (WWW) appeared on the Internet and transformed
the text-based Internet into a graphical rich environment.
 The project team came up with the idea of developing web applets (tiny
programs) using the new language that could run on all types of computers
connected to the Internet.
 In 1994, the team developed a web browser called “Hot java” to locate and run
applet program on Internet.
 Hot java demonstrated the power of new language, thus making it instantly
popular among the Internet users.
 So, while the device for an architecture-neutral programming language provided
the initial spark, the Internet ultimately led to Java‟s large-scale success.
 Java is influenced by C++ it is not an enhanced version of C++.

Difference between JAVA and C++

 JAVA does not support operator overloading.


 JAVA does not have template classes as in C++
 JAVA does not support multiple Inheritances of classes. This is accomplished
using a new feature called “Interface”.
 JAVA does not support Global variables. Every variable and method is declared
within a class and forms part of that class.
 JAVA does not use pointers.

1
 There are no header files in JAVA.
 JAVA has replaces the destroy function with a finalize () function.

FUNDAMENTALS OF OBJECT ORIENTED PROGRAMMING

 OBJECT ORIENTED PROGRAMMING is an approach that provides a way of


modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on
demand.
 Object oriented program organizes a program around its data and a set of well-
defined interfaces to that data.
 An object oriented programming can be characterized as data controlling access
to code.

Some of the features of object-oriented paradigm are:

(i) Emphasis is on data rather than procedure.


(ii) Programs are divided into what are known as “objects”.
(iii) Data structures are designed such that they characterize the objects.
(iv) Methods that operate on the data of an object are tied together in the data
structure.
(v) Data is hidden and cannot be accessed by external functions.
(vi) Objects may communicate with each other through methods.
(vii) New data and methods can be easily added whenever necessary.
(viii) Follows bottom-up approach in program design.

Method Method

Data

Method Method

Object=Data+Methods

2
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING

OBJECTS

 Objects are the basic runtime entities in an object-oriented system. This may
represent a person, a place, a bank account or any item that the program may
handle.
 When a program is executed, the objects interact by sending messages to one
another.
 For example „customer‟ and „account‟ are two objects in a banking program, then
the customer object may send a message to the account object requesting for the
balance.
 Each object contains data and code to manipulate the data.

PERSON ----------- OBJECT


NAME DATA
ROLLNO
MARK1
MARK2
TOTAL( ) METHODS

CLASSES:
Class is a collection of objects.
Once a class has been defined, we can create any number of objects belonging to
that class.
Fruit(class)----> mango(object)

DATA ABSTRACTION AND ENCAPSULATION

 The wrapping up of data and methods into a single unit (class) is known as
Encapsulation.
 These methods provide the interface between the object‟s data and program. The
insulation of the data from direct access by the program is called data hiding.
 ABSTRACTION refers to the act of representing essential features without
including the background details or explanations.

INHERITANCE

 It is the process by which one object acquires the properties of another object..
 In oop, the concept of inheritance provides the idea of reusability; this means that
we can additional features to an existing class without modifying it.
 This is possible by deriving a new class from the existing one. The new class will
have the combined features of both the classes.

3
POLYMORPHISM

 Polymorphism is another important oop concept. It means the ability to take more
than one form.
 More generally, the concept of polymorphism is often expressed by the phrase “
one interface multiple methods”.
 Single Function name perform different task is called function overloading.

Shape

Draw()

Circle Box Triangle

Draw(circle) Draw(box) Draw(triangle)

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
know until the time of the call at runtime.

MESSAGE COMMUNICATION

 An object-oriented program consists of a set of objects that communicate with each


other.
1. Creating classes that defines objects and their behaviour.
2. Creating objects from class definitions.
3. Establishing communication among objects.

4
Message

Sending Object Receiving Object

BENEFITS OF OOPS

1. Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
2. We can build programs from the standard modules that communicate with each
other, rather than having to start writing the code from the scratch. This leads to
saving development time and higher productivity.
3. The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
4. It is possible to have multiple objects to co-exist without any interference.
5. It is possible to map objects in the problem domain to those objects in the program.
6. It is easy to partition the work in a project based on objects.
7. The data centered design approach enables us to capture more details of a model in
an implement able form.
8. Object oriented systems can be easily upgraded from small to large systems.
9. Software complexity can be easily managed.

APPLICATIONS OF OOP

(i). Real systems


(ii). Simulation and modeling
(iii). Object oriented databases.
(iv). Hypertext, hypermedia and expertext
(v) AI and expert systems
(vi). Neural networks and parallel programming.
(vii). Decision support and office automation system.
(viii). CAD/CIM systems

JAVA FEATURES

1.simple.
2.object oriented
3.Compiled and interpreted.
4.robust.
5.secured.
6.architecture neutral.

5
7.portable
8.high performance
9.multi threaded.
10.Dynamic.

Simple:
o Java is a small and simple language.
o Java inherit c syntax and object oriented features of c++.
Object oriented:
o Java is a true object oriented language.
o All program code and data should be within classes and object.
Complied and interpreted:
o A computer language is either complied or interpreted.java combines both
these approaches.
o Java compiler translates source code into bytecode.
o Java interpreted translate bytecode into machine code.

Robust:
o Java is a robust language.
o It is designed for relieving memory management problem and mishandling
exception.
Secured:

ARCHITECTURE NEUTRAL.
o Platform independent- Java programs can be easily moved from one computer
system to another, anywhere and anytime.
o Changes and Upgrades in operating systems, processors and system resources will
not force any changes in Java programs.

PORTABLE

 Java ensures portability in two ways.


 First java compiler generates Byte code instructions that can be
implemented on any machine.
 Secondly, the sizes of the primitive data types are machine independent.

Multithreaded and Interactive

 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.
Dynamic and Extensible
 Java is a Dynamic language. Java is capable of dynamically linking in new class
libraries, methods and objects.
 Memory allocation and deallocation in run time

Java Environment

6
 Java environment includes a large number of development tools, and hundreds of
classes and methods.
 The development tolls 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 API (Application Programming Interface).
E.g.
 AppletViewer (for viewing java applets).
 javac (java compiler)
 java (java Interpreter, which runs applets and application by reading and
interpreting byte code files)
 javah (produces header files for use with native methods)

Text Editor

Java Source HTML


Code javadoc Files

javac

Header
Java Class File javah Files

java jdb

Java Program
Output

 javap(java dissembler, which enables us to convert bytecode files into a program


description)
 jdb (java debugger, which helps us to find errors in our programs)

DATA TYPES:

o The datatype is used for storing the values.

7
o If a value become too big for variable type,it is truncated.

INTEGERS:

 Java defines four integer types byte, short, into long. All of these are signed ,
positive and negative values.
Long- eight bytes
Int- four bytes
Short- two bytes
Byte- one byte.

FLOATING POINT TYPES:

Integer types can hold only whole numbers and therefore we use another type known as
floating point type to hold numbers containing fractional parts such as 23.45. There are
two types of floating point storage.

Float-4 bytes
Double-8 bytes

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 single
character.
 Java support Unicode character set. It define all of the international alphabets.

BOOLEAN TYPE
 Boolean type is used when we want to test a particular condition during the
execution of the program. The two values that a Boolean type can take: true or
false.
JAVA TOKENS:

RESERVED KEYWORDS
 Java language has 60 reserved words as keywords.
 Keywords have specific meaning in java; we cannot use them as names for
variables, methods and so on.
 Java is case sensitive. All keywords are to be written in lowercase letters.
E.g. native case

Eg Auto int
Void long
Goto float
Do Char
IDENTIFIERS:

8
It refer to the name of variables, functions & arrays. Both lowercase & uppercase
are permitted. It cannot use a keyword.
Eg: Name, area, sum…..

CONSTANT:

It refer to fixed data value that do not change during the execution of a program.

Constants

Numeric Constant Character Constant

Integer Real Single String


Constant Constant Character Constant
Constant
INTEGER CONSTANT:

It refer to a sequence of digit.


Three types of integers
1. Decimal
2. Hexadecimal
3. Octal
DECIMAL INTEGER:

It consist of digit from 0 to 9. eg 1789.

HEXADECIMAL :

It must begin with either 0x or 0x and then followed by any digits from 0 to 9.
eg-0x123,0xabcd.

OCTAL INTEGER CONSTANT:

It contain the digit from 0 to 7 eg 0777.

REAL CONSTANT OR FLOATING POINT CONSTANT:

o The numbers are represented by fractional part like 17.548. This is called
floating point constant. eg 0.86

o A real number may also be expressed in exponential notation.

General Format:
Mantissa e exponent

The mantissa may be either decimal or integer.

9
The exponent is an integer number with an optional plus or minus sign. The letter „e‟
separating the mantissa.

Eg.0.65e4

SINGLE CHARACTER CONSTANT:

It is single character enclosed with single quotes.

Eg.‟k‟

STRING CONSTANT:

A string constant is an sequence of character enclosed with in double quotes.

Eg. “hello”.

BACKSLASH CHARACTER CONSTANTS:

 Java supports some special backslash character constants that are used in
o/p methods.
Ex: ‘\b’ Backspace ‘\n’ Newline ‘\t’ Horizontal Tab

VARIABLES:
It is a data name that may be used to store a data value. A variable name can be
chosen by the programmer.

Eg.total
Sum.
RULES:
 The must be begin with letter and remaining character may be alphabets or digits.
 It should not be a keyword.
 White space is not allowed.
 A maximum of 8 should be allowed.
 Upper case and lower case are significant.

DECLARATION OF VARIABLES:

The declaration statement tells the complier 2 things.


1)It tells the complier what the variable name is.
2)It specify what type of data variable name is.

General format:
Data type v1,v2……vn:

10
Eg: int count;
int number, total;

ASSIGNING VALUES THE VARIABLES:

Value can be assigned to variables using the assignment operator „=‟.

General format:
Data type variable name = constant(data value);

Eg:
int X=10;
int N= „a‟;

 The left-hand side of an assignment statement is variable name and right-hand


side of an assignment statement is value.

 It is possible to use multiple assignment operators.

Eg a=b=10;

LITERALS

 Literals in java are a sequence of characters (digits, letters and other characters)
that represent constant values to be stored in variables.
 Java language specifies five major types of literals. They are:
a) Integer literals
b) Floating-point literals
c) Character literals
d) String literals
e) Boolean literals
INTEGER LITERALS:

It refer to a sequence of digit.

Three types of integers

1. Decimal
2. Hexadecimal
3. Octal

DECIMAL LITERALS

11
It consist of digit from 0 to 9. eg 1789.

HEXADECIMAL LITERALS

It must begin with either 0x or 0x and then followed by any digits from 0 to 9.
eg-0x123,0xabcd.

OCTAL INTEGER LITERALS

It contain the digit from 0 to 7 eg 0777.

FLOATING POINT LITERALS:

o The numbers are represented by fractional part like 17.548. This is called
floating point literal. eg 0.86f

SINGLE CHARACTER LITERALS:

It is single character enclosed with single quotes.

Eg.‟k‟

STRING LITERALS:

A string constant is an sequence of character enclosed with in double quotes.

Eg. “hello”.

BOOLEAN TYPE
 Boolean type is used when we want to test a particular condition during the
execution of the program. The two values that a Boolean type can take: true or
false.
OPERATORS & EXPRESSIONS

OPERATOR:
It is a symbol that tells the computer to perform certain mathematical or
logical manipulations.

o Arithmetic operators
o Relational operators
o Logical operators
o Assignment operators
o Increment & decrement operators
o Conditional operators
o Bitwise operators
o Special operators

12
ARITHMETIC OPERATORS:

The operators that works on numbers are called arithmetic operators.

+ addition
- subraction
* multiplication
/ division
% modulo(It is used to give the reminder value )
Integer Arithmetic:

We use integer values in the arithmetic expression is called integer arithmetic.

Eg:
A=5,b=3

Expression value
A+b 8
a-b 2
a*b 15
a/b 1 (decimal point truncated)
a%b 2

eg program

/*calculate months &days*/


class month
public static void main(String args[])
{
int months, days=700;
System.outprintlnf(“enter the days”);
months=days/30;
days=days%30;
System.out.printlnf(“months”+ months+”days”+days);
}

Real Arithmetic:

The arithmetic operation involves only real numbers is called real arithmetic.

A=5.5,b=2.0
Expression value
A+b 7.0
a-b 3.0
a*b 10.0
a/b 2.75

13
Mixed mode Arithmetic:

When one of the operands is real & other is integer .

Eg 15/10.0=1.5

Relational Operators:

These operators are used to compare two or more quantities. the result is either true or false.

Operators 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

General format:

Operand1 relational operator operand2

program
class large
{
public static void main(String args[])
{
int a=9,b=8;
if(a>b)
System.out.println(“ the largest value is ”+a);
else
System.out.println(“ the largest value is”+b);
}

Logical Operator:

The logical operator is used to test more than one condition.

Logical Operator Meaning

&& logical AND


|| logical OR
! logical NOT

Working of AND,OR:

14
Op1 op2 op&&op2 op1||op2

0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

Working of OR:

Op1 !op1

0 1
1 0

Assignment Operator:

The assignment operator is used to assign the values to the operand.

General format:

Variable operand = expression

Shorthand Assignment:

The shorthand assignment operator is op=.


Op->operator.

Statement with simple statement with shorthand


Assignment operator operator

a=a+1 a+=1;
a=a-1 a-+1;
a=a*(n+1) a*=n+1;

Advantages:

 The statement more concise and easier to read.


 The left-hand side variable need not to repeated on the right-hand side.
 The statement is more efficient.

Increment And Decrement Operator:

15
 The increment is operator (++) add one and decrement operator(--) is subtract
one.

Eg.
++m =>m=m+1=>m+=1.
M++=>m=m+1=>m+=1.
 In general m++,++m are same but when they are used in assignment statement
they have different meanings.

 If the operator placed before the operand it is known as preincrement operator.if


the operator placed following the operand it is known as post increment operator.

For eg.

M=5 m=5;
Y=++m; y=m++;
Y=6,m=6. y=5,m=6.

 A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on left.

 A postfix operator first assign the value to the variable on left and then increment
the operand.

Conditional Operator:

It is a ternary operator and takes three operands. The “?:” is joinly known as
conditional operator.

General format:

Exp1?Exp2:Exp3

Exp -> expressions.

 Exp1 is evaluated and if it is true,exp2 is evaluated and the value is assign to


variable.
 Exp1 is false exp3 is evaluated and the value is assign to variable.

Bitwise Operator:

It is used for manipulation of data at bit level.


It may not be applied tp float or double.

16
Operator meaning

& bitwise AND


| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right

Bitwise Table:
A B A|B A&B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0

Left Shift:

 The Left shift operator <<, shifts all of the bits in a value to the left a
specified number of times.
Value <<m
 Here num specifies the number of positions to the left-shift the values in
value that is the <<, moves all of the bits in the specified value to the left by
the number of bit positions specified by num.
Right Shift:
 The right shift shifts all of the bits in value to the right a specified number
of times. Its general form
Value >> num.
Int a=32; a=a>>2; a will now have 8.
Special Operators:

1. Comma(,)
2. Sizeof.
3. Pointer(&.*).
4. Member selection(. And->).
Comma Operator:

 It is used to link the releted expression together.


 It is evaluated from left to right.

17
Eg.
value=(n=1,m=10,n+m);
The Sizeof Operator:

It is compile time operator and when it is used in operand , it the number of bytes
the operand occupies.

Eg M=sizeof(sum).
N=sizeof(longint).

Expression:
An expression is combination of operator and operands.
Three types of expressions.

 Arithmetic expression.
 Relational expression.
 Logical expression.

Arithmetic Expression.:

An arithmetic expression involving only arithmetic operators is known as


arithmetic expression

Exp1 Arithmetic Operator:Exp3

Precedence Of Arithmetic Operator:


First Priority:()

The quantity inside the parenthesis have highest priority.

Second Priority:*/%

The * and / have equal priority and are evaluated from left to right in the order of
occurrence.

Third Priority:+-

The + and - have equal priority and are evaluated from left to right in the order of
occurrence.

Arithmetic Expression Are Of Three Types :

1. integer expression
2. real expression

18
3. mixed mode expression

Integer Expression:

An arithmetic expression involving only integer operands is known as an integer


expression.

Let a=2,b=3,c=4,d=5,e=6
Eg 1)
(a+c)/c*d
Step 1). (2+4)/4*5
Step 2). 6/4*5
Step 3).1*5
Step 4). 5

Eg 2)
(a+c)/(c*d)
Step 1). (2+4)/(4*5)
Step 2). (6)/(4*5)
Step 3). (6)/(20)
Step 4). 0

Real Expression:

If all the operands in an expression are of real type the expression is known as real
expression. Where a,b, c, d, are real variables
Eg
Let a=.0 ; b=15.0;c=2.5

=10.0+15.0*2.5
=10.0+37.5
=47.5

Mixed Mode Expression:

If the operands in an expression are of different types, the expression is known as


mixed mode expression for evaluating a mixed mode expression, the lowest type
operands is converted to highest type and the result is of highest type.
Eg:
a+b*c
let a=10,b=15,c=2.5
=10+15*2.5
=10+37.5
=47.5

Relational Expression:

19
 An expression containing relational operators is known as the relational
expression.
 It is also used to combine two arithmetic expression.
 The result of a relational expression is either true or false. True is taken as one
and false is taken as zero.

The general form is

Exp1 relational operator Exp2

E.g.: a=5,b=6
a>b = false (0)
a!=b = True (1)

Logical Expressions:

 An expression containing logical operators is known as the logical expression.


 It is used to combine two or more relative expression.
 The result of a logical expression is either true or false.

The general form is

Exp1 logical operator Exp2

E.g. 1:
(test 1 > 40)||(test 2 > 40)
Mark = 5

E.g. 2:
(Mark 1 > 40)&& (mark 2 >40) && (mark 3 > 40)
R = „p‟

Priority Of Logical Operator:

First priority: logical NOT (!)


Second priority: logical AND (&&)
Third priority: logical OR (||)

20
COMMAND LINE ARGUMENTS

Command Line arguments are parameters that are supplied to the application
program at the time of invoking it for execution. The execution of the command line as
follows

java Test //
Here, Test is the name of the program we can write java programs that can receive
and use the arguments provided in the command line.
Example:
public static void main (String args[])

args is declared as an array of string (known as string objects).any arguments


provided in the command line are passed to the array args as its elements.
We can simply access the array elements and use them in the program as we wish.
For example, consider the command line

java Test BASIC FORTRAN C++ Java

This command line contains four. These are assigned to the array args as follows:
BASIC --------------> args [0]
FORTRAN---------> args [1]
C++ -----------------> args [2]
Java-----------------> args [3]

Example program: Use of command line arguments

/*
* this program uses command line
* arguments as inputs.
*/
Class ComLineTest
{
public static void main(String args[ ])
{
int count,i=0;
string string;
count = args.length;
system.Out.println(“Number of arguments = “ count);
while ( i < count)
{
string = args[ i];
i = i+1;
System.out.println(i+ “ : “ + “Java is “ + String+ “!”);
}
}
}

21
CONTROL STATEMENTS:

The decision making statement are used to control the flow of execution.
 If statement.
 switch statement.
 conditional operator statement.

If Statement:

It is a decision making statement and is used to take a decision based on a given


condition.
The general form is,

If(condition)
{
Statement-1;
}
If the condition is true, the statement-1 will be executed and the control is
transferred to the statement-n. If the condition is false, the block is skipped.

Example:
class positive
{
public static void main(String args[])
{
int a=9;
if(a>0)
System.out.println(“a is positive”);
}
The if statement takes the below forms.

1. simple if statement.
2. if-else statement.
3. nested if-else statement.
4. else if ladder statement.

Simple if statement:
General form:
if(condition)
{
Statement-1;
}
Statement-n;

 If the condition is true the statement-1 will be executed and the control is
transferred to the statement-n.

22
 If the condition is false if block is skipped and statement-n will be executed.

class mark
{
public static void main(String args[])
{
int marks=89;
char category=sports;
if(category==sports)
{
marks=marks+5;
}
System.out.println(marks);
}
If-Else Statement:
It is a two way decision making statement; it is used to execute a set of
statements based on a condition.

The general form is,

if(condition)
{
True block statement;
}
else
{
False block statement;
}
Statement-n;

 If the condition is true, the true block statements will be executed.


 if the condition is false, the false block statements will be executed.
 In either care either the true block or the false block will be executed.

eg1:
/*largest of two numbers*/
class large
{
public static void main(String args[])
{
int a=9,b=6;
if(a>b)
System.out.println(“a is large“);

23
else
System.out.println(“b is large”);
}
eg2:
/*area of square and circle*/
class square
{
public static void main(String args[])
{
int code=1;
float area=8a,side=6,r=3;
if(code==0)
{
System.out.println(“square”);
area=3.14*r*r;
System.out.println(area);
}
else
{
System.out.println(“circle”);
area=side*side;
System.out.println(area);
}
}
Nested if-else statement or dangling else:

If an if-else statement is placed with in another if-else statement, it is a nested if-


else statement.
The general for is,

If(condition-1)
{
If(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-n;

Execution:

24
 If conditions-1 is true than condition-2 is check. If condition-2 is true statement-1
will be executed and the control transferred to statement-n.
 If condition -1 is true and condition-2 is false,statement-2 will be executed.
 If condition-1 is false, statement-3 will be executed.

Eg:
1)/*Largest of three numbers*/
class largest
{
public static void main(String args[])
{
int a=9,b=6,c=5;
if(a>b)
{
if(a>c)
{
System.out.println( a);
}
else
{
System.out.println( c);

}
}
else
{
if(b>c)
{
System.out.println( b);
}
else
{
System.out.println( c);

}
}
input:
9
6
5
output:
largest number=9

2)/*print the color*/


Class color
public static void main(String args[])
{

25
int code=1;
if(code=1)
if(code=2)
if(code=3)
System.out.println(“yellow”);
else
System.out.println(“blue”);
else
System.out.println(“black”);
else
System.out.println(“white”);
}

else-if ladder:
It is the multi path decision making statement.
The general format:

If(condition-1)
{
If(condition1)
Statement-1;
else-if(condition-2)
statement-2;

else-if(condition-3)
statement-3;
………..
…………
}
else
default statement;

Execution:
 As soon as a condition is true the statement associated with the
condition is executed, and the control is transferred to statement-n.
 If all the n conditions are false the default statement will be
executed.

Eg:
/*Write a program to process student results based on the given data.*/

class marklist
{
public static void main(String args[])

26
{
int m1=89, m2=90, m3=99, m4=90, m5=80;
float avg;
avg=(m1+m2+m3+m4+m5)/5;
System.out.println(“tot”+tot+”avg”+avg);
if(avg>79)
System.out.println(“Distinction”);
else if(avg>59)
System.out.println (“First class”);
else if(avg>49)
System.out.println (“Second class”);
else if(avg>39)
System.out.println (“Third class”);
else
System.out.println (“Fail”);
}

Conditional Operator Statement:

It is a operator and is used to make two way decision


General Format:

exp1?:exp2:exp3

exp1,exp2,exp3-> expressions.
 If expression1 is true, expression 2 is evaluated and value is assigned to left hand
side variable.
 If expression1 is false, expression3 is evaluated and value is assigned to left hand
side variable.
 It should be used in an assignment statement.

Eg:
1)/*largest of two numbers*/
class large
{
public static void main(String args[])
{
int a=7,b=6,c;
c=(a>b)?a:b;
System.out.println(c);
}
2)/*Write a program that uses conditional operator for the below data.*/
Y={1.5x+3 for x<=2x+5 for x>2
class condition

27
{
public static void main(String args[])
{
int x=6;
float y;
y=(x<=2)?:(1.5*x+3)2*x+5);
System.out.println (y);
}

Switch statement:

The switch statement is used to select one operation from many operations.
The general form is,

switch(expression)
{
case label1:
block1 statement;
break;
case label2:
block2 statement;
break;
…….
default:
default block;
}
statement-n;

Execution:

 Where expression is an integer expression or a single character constants.


Block1,Block2..etc, are a group of statement or may be a single statements. There
is no need to put braces around the blocks.
 Label1,Label2…etc, are case labels and must be unique.
 The case labels may be integer constants or single character constants. The case
labels should end with the colon.
 The switch statement tests the value of the expression against the case labels.
When a match is found a block of statements associated with the case is executed.

28
 The break statement denoted the end of the case and causes an exits from the
switch statement and the control is transferred to the default case is optional.
 If no match is found the default block will be executed.

1)/*PROGRAM*/
class add
{
public static void main(String args[])
{
char choice=‟-„;
float a=4,b=3,c;
switch(choice)
{
case „+‟:
c=a+b;
break;
case „–„:
c=a-b;
break;
case „*‟:
c=a*b;
break;
case „/‟:
c=a/b;
break;
}
System.out.println (c);
}
ITERATION STATEMENT

While loop:
It is an entry control loop.The genaral form is
Syntax:

While(condition)
{
Body of the loop;
}

Execution:
 If the condition is true the body of the loop will be executed.
 If the condition is false the control is terminate at the loop.

/*sum of digits*/
class sum
{

29
public static void main(String args[])
{
int num=123,r,q=0;
while(num>0)
{
r=num%10;
q=q+r;
num=num/10;
}
System.out.println (num);
}

DO…..Whileloop:
It is an exit controls loop.
The general form is

Do
{
Body of the loop;
}
While(condition);

Execution:
o The body of the loop is executed and then the condition is check.
o If the condition is true the body of the loop will be executed. otherwise the
control is terminated
o Even if the condition false at the begin the loop is executed for the first
time
/*program*/
class sums
{
public static void main(String args[])
{
int sum,n=5,i;
sum=0;i=1;
do
{
sum=sum+i;
i++;
}
while(i<=n);
System.out.println (“the sum of first 5 numbers”+n+sum);
}

For Loop:
It is entry control loop.
General Form:

30
for(initialiazation;condition;increment and decrement)
{
body of loop;
}

Execution:
 The initialization of the control variable is done using the assignment statement.
 The value of the control variable is tested using the test condition.
 If the condition is true body of the will be executed.
 If the condition is false the body of the loop will not executed and the control is
transferred to the statement following the loop.
 The control variable is increment or decrement using the increment or decrement
section and the new value is tested against to the condition.
/*Fibonacci*/
class Fibonacci
{
public static void main(String args[])
{
int f0=0,f1=1,f2,n=5,i;
System.out.println (f0);
System.out.println(f1);
for(i=0;i<=n;i++)
{
f2=f0+f1;
System.out.println (f2);
f0=f1;
f1=f2;
}

/*factorial*/
class factorial
{
public static void main(String args)
{
long int i,n=5,fact=1;
clrscr();
for(i=1;i<n;i++)
{
fact=fact*i;
System.out.println(“factorial”+fact);
}
}
Nested For Loop:
It is entry control loop.

31
General Form:
for(initialization; condition; increment and decrement)
{
for(initialization; condition; increment and decrement)
{
body of loop;
}
}

/*to find the addition of 2 matrix*/


class matrix
{
public static void main(String args[])
{
int matrix1[][]=new int[3][3],matrix2[][]=new int[3][3], ans[][]=new int[3][3],i,j;
matrix1[0][0]=3;
matrix1[0][1]=23;
matrix1[0][2]=23;
matrix1[1][0]=31;
matrix1[1][1]=32;
matrix1[1][2]=13;

matrix2[0][0]=4;
matrix2[0][1]=5;
matrix2[0][2]=6;
matrix2[1][0]=31;
matrix2[1][1]=2;
matrix2[1][2]=1;
for(i=0;i<3;i++)
{
for(j=0;j<3;++)
{
ans[i][j]=matrix[i][j]+matrix[i][j];
System.out.println(ans[i][j]);
}
System.out.println (“\n”);
}
}

Additional Features Of For Loop:

1)more than one variable can be initialized in the initialization section.


The variable must be separated by comma.
eg.
for(i=1;sum=0;i<=n;i++)
sum=sum+i;
2) More than one condition can be checked.
eg.

32
for(i=1;sum=0;i<=5&&sum<=10;i++)
sum=sum+i;
3) It is possible to use assignment statement in the initialization and increment
section.
eg.
for(x=(m+n)/2;x>0;x=x/2)
4) It is possible to omit one on more section but the test condition must be stated.
eg.
for(i<=10)
{
System.out.println (“%d”,i);
i++;
}
5)It is possible to set time delay the loop.
eg.
for(j=1000;j>=0;j--)
GOTO Statement:

o It is branching statement and is used to transfer the control to any


statement.
o It is a unconditional statement, since it is simply transfer the control
without checking any condition.

General format

goto label name

label name-> variable name.


Types:

1)forward jump
2)backward jump.

Forward Jump

If the label statement is placed after the goto statement.

General format

goto label;

label: stat-x

In the forward jump a set of statement are skipped and the control is transferred to
label statement. /*program*/

33
class number
{
public static void main(String args[])
{
int number=4;
if(number<=5)
goto last;
else
{
System.out.println (“the number is not less than 5”);
}
last: System.out.println (“the number is less than 5”);
}

Backward Jump

If the label statement is placed before the goto statement.

General format
Label: stat-x

Goto;repeatly executed. The statements are executed


In the backward jump a set of statements
infinite number of times. To terminate the infinite execution the user has check the
condition.

/*program*/

class backward
{
public static void main(String args[])
{
read:int number=3;
if(number<=5)
System.out.println(“the number is less than 5”);
else
{
goto read;
}
}
Statement Label Vs Case Label

Statement label Case label


1)the label must be variable names 1)the case labels may be integer constant
or single character constants
2)the labeled statement can be placed 2)the case labeled should be placed after
anywhere in the program the case keyword

34
ARRAY
It is a collection of related data items and stored in the same data type.
types of arrays:
 One dimensional array.
 two dimensional array.
 multi dimensional array.
One Dimensional Array:
Declaration Of One Dimensional Array:

A list of items can be given one variable name using only one subscript. The
subscript must be integer constant.

general format:

data type arrayname[size];

eg.
int number[15];
char name[10];
storage process:
number[0]=23;
number[1]=33;
number[2]=53;
number[3]=63;
number[4]=73;

char name[10];
we read “welldone” and it stored as follows,
name[0]=‟w‟;
name[1]=‟e‟;
name[2]=‟l‟;
name[3]=‟l‟;
name[4]=‟‟;
name[5]=‟d‟;
name[6]=‟o‟;
name[7]=‟n‟;
name[8]=‟e‟;
name[9]=‟\0‟;->null character.
/*read 5 number and print the number*/
Class array
{
Public static void main(String args[])
{
int a[2],i;

35
a[0]=9;
a[1]=8;
a[2]=7;
for(i=0;i<2;i++)
{
System.out.println(a[i]);
}
}

Initialization Of One-Dimentional Array:


After an array is declared its elements must be initialized. otherwise they
will contain “garbage”.
general format:

type array_name[size]={list of values}

The values in the list are separated by commas.


for eg.
int number[3]={1,5,7}
the value stored as,
number[0]=1;
number[1]=5;
number[2]=7;
program:
/*initialiazing and printing the value*/
Class array
{
Public static void main(String args[])
{
int i,a[4]={4,6,7,8};
for(i=0;i<4;i++)
{
System.out.println(a[i]);
}
}
two dimensional array:
general format:

type array_name[size][size];

eg.
int matrix[m][n];
m->rows;
n->columns;
the array can be declared by passing of values of numbers of rows and
number of columns as subscript values.

36
eg. column

rows

Initialization Arrays:
The values can also be initialized by enclosed with in braces.
eg.
int array[3][4]={{0,1,2,3},{4,5,6,7},{8,9,10,11}};
(or)
int array[3][4]={0,1,2,34,5,6,78,9,10,11};program:
1)/*to find the addition of 2 matrix*/
Class array
{
Public static void main(String args[])
{
int a[20][20],i;
a[0][0]=8;
a[0][1]=7;
a[1][0]=8;
a[1][1]=7;
for(i=0;i<2;i++)
{
for(j=0;j<2;i++)
{
System.out.println(a[i][j]);
}
}
}

SIMPLE JAVA PROGRAM


class sample
{
public static void main(String a[])
{
System.out.println(“Welcome to java”);
}
}

THE FIRST LINE:

 Class one declares a class, which is an object oriented construct. Class is a


keyword and declares that a new class definition follows.

THE THIRD LINE

37
 Public static void main(String a[]) defines a method named main.
 Every java application program must include the main() method.
 This is the starting point for the interpreter to begin the execution of the program.
 A java application can have any number of classes but only one of them must
include a main method to initiate the execution.
 Public the keyword Public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes. This is similar
to the C++ public modifier.

Static:

 Neat appears the keyword static, which declares this method as one that belongs
to the entire class and not part of any objects of the class.
 It (main) must always be declared as static since the interpreter uses this method
before any objects are created.
Void:

 The type modifier void states that the main method does not return any value.

Comment Statement

 It 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.
E.g.:
// this is a sample program
/* this is a java program */

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.
E.g.: package student;

Import statement:

The next thing after a package statement may be a number of import statements.
This is similar to the #include statement in C.
E.g.: import student.test;

Interface Statements:

 It is like a class but includes a group of method declarations. It is used in


implementing multiple inheritances.

Class definitions
 These are the primary and essential elements of a java program.

38
The Byte code

 The key that allows java to solve both the security and the portability problems
are that the output of a java compiler is not executable code.
 Rather it is Byte code. Byte code is a highly optimized set of instructions
designed to be executed by java runtime system, which is called the Java Virtual
Machine (JVM).
 That is in its standard form, the JVM is an interpreter for Byte code. This may
come as a bit of a surprise.
 As you know C++ is compiled to executable code. In fact most modern
languages are designed to be compiled, not interpreted-mostly because of
performance concerns.
 However, the fact that a java program is executed by the JVM helps solve the
major problems associated with downloading programs over the Internet.
 Translating a java program into Byte code helps make it easier to run a program
in a wide variety of environments.
 The reason is straightforward: only the JVM needs to be implemented for each
platform.
 Once the runtime package exists for a given system, any java program can run to
it. Remember, although the details of the JVM will differ from platform to
platform, all interpret the same java Byte code.
 If a java program were compiled to native code, then different versions of the
same program would have to exist for each type of CPU connected to the Internet.
 This is, of course, not a feasible solution. Thus, the interpretation of Byte code. Is
the easiest way to create truly portable programs.
 The fact that a java program is interpreted also helps to make it secure.
 Because the execution of every java program is under the control of the JVM can
contain the program and prevent it from generating side effects outside of the
system.

39

You might also like