0% found this document useful (0 votes)
16 views43 pages

Java_Unit-1

Java lang

Uploaded by

Piyush Soni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views43 pages

Java_Unit-1

Java lang

Uploaded by

Piyush Soni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

UNIT-I Introduction

1 Introduction

JAVA History:
• It is true object oriented programming language
• It was developed by Sun Microsystems of USA in 1991.
• It was specially design for the software for electronics devices such as TV, VCRs, Mobile, DVD,
etc.
• Initially name of JAVA was Oak.
• This new language developed by removing certain drawbacks of C and C++ such as reliability
and portability.
The following discussion shows some important milestones in the development of Java.
Year Development
1990 Sun Microsystems decided to develop special software for electronic devices such as TV,
VCRs, Mobile, DVD etc. A team member of Sun Microsystems was starting to work on
this project.
1991 A green project team announced a new language named “Oak” based on Object oriented
programming concepts. This name was given by Mr. James Gosling who was leader of
this team.
1992 A green project team demonstrated the application of the new language.
1993 The Green project team developed Web applets using a new language that could run on
all types of computers connected to internet. This development becomes a very useful for
World wide web on the internet for converting text data into graphical form (Applet
form).
1994 The team developed a Web browser called “HotJava” to locate and run applet program
on internet. This Web browser demonstrated the powerful use of this language. That why
this language becomes a popular for the internet user.
1995 Oak was renamed to “JAVA”. Many popular Web browser companies such as Netscape,
Microsoft announced their support to java.
1996 Java becomes a leader for Internet programming.

Java Features:
Sun Microsystems describes Java with the following features.
1. Complied and Interpreted
2. Platform-Independent and Portable
3. Object Oriented
4. Robust and Secure

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 1


UNIT-I Introduction

5. Distributed
6. Simple, Small and Familiar
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
10. Platform-neutral Language

1. Complied and Interpreted:


A computer language program is usually either compiled or interpreted. Java combines both of these
approaches.

• Java compiler translates source code into Bytecode instructions.

• Java Interpreter generates a machine code from the Bytecode. This will run a Java program.
From this we can say that Java is both a compiled and interpreted language.
2. Platform-Independent and Portable:

• Java program can be easily moved from one computer system to another, anywhere and anytime.
There are any changes and upgrades in operating system, processors and system resources will
not force any changes in Java program. This is the reason why Java becomes a popular language
for programming on internet which interconnects different kinds of computer systems
worldwide.

• Java generates a Bytecode instruction that can be executed on any machine. The size of the
primitive data types are machine independent.
3. Object Oriented:

• It is true object oriented programming language. Almost everything in java is an Object. All
program code and data reside within objects and classes. Java comes with an extensive set of
classes arranged in packages that can be used in our programs by inheritance.
4. Robust and Secure:

• It is a robust language. It provides a many safeguards to ensure reliable code. It has strict
compile time and Run time checking for data types. It provides the concepts of Exception
handling that captures series of errors and removed any risk of crashing the system.

• Java provides a security against viruses and misuse of computer resources. It is important to
provide security for a language that is used for programming on internet. There are possibilities
of viruses and misuse of resources is everywhere. The absence of pointers in Java, nobody can

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 2


UNIT-I Introduction

direct access memory location without prior permissions. Java systems verify all memory access
and also ensure that no viruses are communicated with an applet.
5. Distributed:

• Java is a distributed programming language. It has ability to share both data and programs. Java
application can open and access remote object on internet as easily as they can do in local
system.
6. Simple, Small and Familiar:

• Java is small and simple language. Java does not include so many features of C and C++
language. It means that some sources of unreliable code are not part of java. For

• Example, java does not use pointers, preprocessors, header file Goto statement and so many
others.

• Java is familiar to the existing programmers. The java was designed based on C and C++
languages. Therefore, it is familiar to the existing programmers.
7. Multithreaded and Interactive:

• Java support multithreading programming. Multithreading means handling multiple tasks


simultaneously. Multiple tasks can execute at a time. For example, we are listening to an audio
clip and at the same time download an applet from the remote computer.

• Java provides smoothly running interactive applications. The features of multithreading


improves the interactive performance of an application.
8. High performance:

• Java performance is impressive due to the use of intermediate bytecodes. Java speed is
comparable to the same as C\C++. It reduces overheads during runtime. The overall execution
speed of Java program increases, due to multithreaded programming.
9. Dynamic and Extensible:

• Java is a Dynamic language. It supports the dynamic linking in new class libraries, methods and
object. Java can determine the type of class through query, making possible to either dynamically
link or abort the program, depending on the response.

• Java is extensible language. Java programs supports functions written in other languages such as
C and C++. These functions are known as native methods. They are linked dynamically at
runtime.
10. Platform-neutral Language:

• It is most important feature of a java program. Programs developed in Java can be executed
anywhere on any system. It does not depend on any particular hardware or operating system.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 3


UNIT-I Introduction

Java Virtual Machine (JVM):

All language compilers translate source code into machine code for a specific computer. Java compiler
is also does the same thing but slightly differently. Java compiler converts the source code into
bytecodes for a machine. This machine is called the Java Virtual Machine (JVM). JVM exist only
inside the computer memory and does all major functions of a real computer.
The following figure shows the process of compiling a java program into bytecodes which is also
referred to as virtual machine code.

Java Program Java Compiler Bytecode

Source code Virtual machine


Figure: Process of compilation
The virtual machine code is not machine specific. The machine specific code is generated by
java interpreter. Java interpreter reads the bytecode files and translates them into machine code for the
specific machine. The java interpreter is different for different machine.

Bytecode Java Interpreter Machine Code

Virtual machine Real machine


Figure: Process of converting bytecode into machine code

Java Program Structure:


The following shows the general structure of a java program.

Documentation section
Suggested
Package statement

Import statements

Interface statements Optional

Class definitions

Main method class


{
Essential
Main method definition
}

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 4


UNIT-I Introduction

1. Documentation section:

• The documentation section consists of a set of comment lines giving the names of the program,
the author and other details.
Java supports three types of comments:
A. Single line comment : It begins with // and ends at the end of the line.
B. Multiline comment : It begins with /* and ends with */.
C. Documentation comment : It begins with /** and ends with */. It is used for generating
documents automatically.
2. Package statement:

• The package statement is the first statement in a java file. This statement declares a name of the
package. The package statement is optional. E.g. package student ;
3. Import statement:

• This will contains number of import statements. It is similar to the #include statement in C\C++
language. It is an optional statement. The import statement must be written before any class
declarations.
E.g. import java.lang.Math ;

• It imports the class math and this class can be directly used in program.
4. Interface statement:

• The interface statement is used for achieving the multiple inheritances in Java. It is an optional
statement. It is same as a class and contains group of methods.
5. Class definitions:

• A java program may contain multiple class definitions. The class definition contains the
declarations of multiple classes. Classes are the elements of a java program.

• These classes are used to map the object of real world problems. The number of classes depends
on the complexity of the problem.
6. Main method class:

• Every java program must contain one main method class which contains main function. The
execution starts with opening curly brace “{“and ends with a closing curly brace “}”of main()
function.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 5


UNIT-I Introduction

Simple Java Program:


The following is a very simple Java program that prints “Good Morning” on the screen.
// To print “Good Morning” on screen
class test
{
public static void main( String args[ ] )
{
System.out.println( “Good Morning”) ;
}
}
Let us discuss the Java program line by line.

Comments line

• The first line is the comment lines starting with ‘//’ character. Java supports both single line and
multiple line comments available in C++.
Class declaration

• The next line


class test
declares a class, which is an object oriented construct. Here, class is a keyword and test is a java
identifier that specifies the name of the class.
Opening brace

• Every class definitions in java begins with an opening curly brace “{“ and end with matching
closing curly brace “}”. This is similar to C++ class construct except semicolon at closing brace.
The main method

• The next line


public static void main( String args[ ] )
defines a main() method of a java program. Every java application program must contains the
main() method. This is the starting point for the java interpreter to begin the execution of the
program. The java application program can have any number of classes but only one of them
must include a main() method. Java applet will not use the main() method.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 6


UNIT-I Introduction

This line contains following keywords:

• Public :
o It is an access specifier. It means that main() method is accessible to all other classes.

• Static :
o It declares that the main() method belongs to the entire class and not a part of any object
of the class. The main() method must always declared as static since the interpreter uses
this method before any objects are created.

• Void :
o It means that main() method does not return any value.

• String args[ ] :
o All parameters to a method are declared inside a pair of parentheses. String args[ ]
declares a parameter name args, which contains an array of object of the class String.
The output line

• The following statement


System.out.println( “Good Morning”) ;
is similar to the printf() statement of C language. It will print string “Good Morning” on the
screen. Every java statements must end with a semicolon.

Implementing a Java program:


Implementing a Java program involves a series of steps.
They include:
1. Creating the program
2. Compiling the program
3. Running the program

1. Creating the program:


Write down the following code into any text editor.
// To print “Good Morning” on screen
class test
{
public static void main( String args[ ] )

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 7


UNIT-I Introduction

{
System.out.println( “Good Morning”) ;
}
}
Now, save this program in a file as test.java. This file is known as source file.
2. Compiling the program:

• Java compiler (javac) compiles the source file.


C:\jdk1.3\bin>javac test.java

• This command compiles test.java and creates a new file test.class. The test.class contains the
bytecodes of the program.
3. Running the program:

• Java interpreter (java) runs the class file.


C:\ jdk1.3\bin >java test
Good Morning
C:\ jdk1.3\bin >

• This command gives the output the above java program.

Java token:
The smallest individual units in a Java program are known as token. OR The character together makes
special symbols or word known as token.
Java language includes five types of tokens and they are:
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

1. Keywords

• Keywords are essential part of language definition. They implement specific features of the
language.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 8


UNIT-I Introduction

• All keywords are written in lower case letters. Java language has reserved 60 words as keywords.
The keyword has specific meaning in language, so we can not use them as name of variable,
class, method and so on. Java does not use many of the C and C++ keyword. Java adds new 27
keywords that are not in C and C++.
2. Identifiers:

• Identifiers are programmer-designed tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a Java program.

• Java identifiers follow the following rules:


1. They can have alphabets, digits, underscore and dollar sign character.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
3. Literals:

• A literal in java represents constants values to be stored in variables. A Java language has five
types of literals. They are:
1. Integer literal
2. Floating point literal
3. Character literal
4. String literal
5. Boolean literal
4. Operators:

• "An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations"

• Java operators can be classified into a number of categories. They include


o Arithmetic Operator
o Relational Operator
o Logical Operator
o Assignment Operator
o Increment and Decrement Operator
o Conditional Operator
o Bitwise Operator
o Special Operator
5. Separators:

• Separators are symbols used to indicate where groups of code are divide and arranged. The
following are list of separators with their functions.

Name Uses

Parentheses () - To give higher precedence in expression,


- To call a method,

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 9


UNIT-I Introduction

- Parameters define in a method definition,


- Type casting
Braces { } - To initialize an arrays
- To define a block of code
Brackets [ ] - To declare array types
- To dereferencing array values
Semicolon ; - Separate statements

Comma , - Separate statements in for loop


- Separate variables in declaration statements
Period . - Separate class and method name
- Separate packages from sub-packages

Constant:
"A constant is a fixed value that can be unchanged during program execution.”
Types of constant:
Java support several types of constant as shown below.

• Numeric Constants
o Integer Constants
o Real Constants

• Character Constants
o Single character constants
o String constants

Numeric Constants:
Integer Constants:
An integer constant is a sequence of digits. There are three types of integer, namely decimal octal and
hexadecimal.

• Decimal integer constant: It consists of a set of digits 0 through 9, preceded by an optional


minus sign.
Valid Examples:
123, -123, 0, 12345, +45.
Invalid Examples:
12 345 (Space not allowed)
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 10
UNIT-I Introduction

1, 2345 (Comma not allowed)


$123 ($ not allowed)

• Octal integer constant: It consists of a set of digits 0 through 7, preceded by 0.


Valid Examples:
037, 0435, 0, 012, 065

• Hexadecimal Integer Constant: It consists of a set of digits 0 through 15, preceded by 0x or


0X.The letters A through F represents the numbers 10 through 15 respectively.
Valid Example:
0x2, 0X2, 0x9F, 0xbca, 0x
Real Constants:
It is also known as Floating-point constants. It has a decimal point or an exponent sign (e) or both.
• Decimal Notation: Here, the number is represented as a whole number, followed by a decimal
point and a fraction part. It is possible to omit digits before and after the decimal point.
Valid Example:
123.45 .123 123. -.78 -0.78

• Exponential Notation: It is useful in representing numbers whose magnitudes are very large or
small. It consists of a mantissa and an exponent.
The general form is
mantissa e exponent

▪ The mantissa is either a real number expressed in decimal notation or an integer.


▪ The exponent is an integer number with an optional plus or minus sign.
▪ The letter e separating the mantissa and the exponent can be written in either lowercase
or upper case.
Valid Example:
0.65e4 12e-2 1.5e+5 -1.2E-l
Invalid Example:
3.4e.4 (Exponent must be an integer)
3e 8 (Blank not allowed)
2.00e4 (comma not allowed)

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 11


UNIT-I Introduction

Character Constant:
Single Character Constant:

• A character constant is enclosed in single quotes.


Valid Examples:
'a' 'A' ‘5’ ‘ ‘
Invalid Examples:
'aa' 'Aa' '56'

• Single characters constant have an integer values known as ASCII values.


String Constant:

• A string constant is a sequence of characters enclosed in double quotes.

• The characters may be letters, numbers, special characters and blank space.
Valid Example:
"Hello" "F.Y.B.CA." “2004” “?....” “ 1 + 2"

• Remember that 'A' and "A" are different.

Variable:
A Variable is an identifier whose value can be changed during program execution.
Rules for writing variable names:
Variable names may consist of letters, digits, underscore (_) and dollar character with the following
rules.
1. They must not begin with a digit.
2. It is case-sensitive. It means lower case and uppercase are different. E.g. the variable name Total
and total both are different.
3. It should not be a keyword.
4. White space (Blank space) is not allowed.
5. It can be of any length.
Some examples
average, height, total_height, classStrength.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 12


UNIT-I Introduction

Data types in Java:


• Every variable in java has data type.
• Data types specify the size and type of values that can be stored.
• Java language is rich in its data types.
Data types in Java have following categories:

Data types in Java

Primitive Non-Primitive

( Built-in or Intrinsic ) ( Derived )

Numeric Non-numeric Class Interface Array

Integer Floating-point Characte Boolean


r

Primitive:
Integer data type:
Java supports four types of integers. They are byte, short, int and long. All of these are
signed integers. It means that the value of a variable is either negative or positive. Java does not
support unsigned integers.
The following table shows the size and range of integer data types in java.

Type Size(in Byte) Minimum value Maximum value

byte 1 -128 127

Short 2 -32768 32767

Int 4 -2,147,483,648 2,147,483,647

Long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating-point data type:


Java supports two types of floating-point d ata type. They are float and double.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 13


UNIT-I Introduction

The float data type represents single-precision numbers while double is double-precision
numbers.
The following table shows the size and range of floating-point data types in java.

Type Size(in Byte) Minimum value Maximum value

float 4 3.4e-038 3.4e+034

double 8 1.7e-308 1.7e+308

Character data type:


Java provides a character data type by char keyword. The size of char data type is 2 bytes but it
can only store only single character.

Boolean data type:


There are only two values that a Boolean data type can take: true or false. The size of Boolean
data type is 1 bit. The default value of this data type is false.
It is normally used in conditions of selection statements.

Declaration of variables:
A variable can be used to store a value of any data type.
The general form variable declaration is
data type variable1, variable2, . . . . . . VariableN ;
Here, data type is any valid data type of java such as int, short, float, char etc. and variable1,
variable2,…….VariableN are any valid variable names.
Two or more variable names are separated by comma. A declaration statement must end with a
semicolon.
Examples of declaration of variables:
byte b1;
int a, b, total;
char c1, c2, gender;

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 14


UNIT-I Introduction

Giving values to variables


There are two ways to give a value to a variable after its declaration.
They are:

• By using assignment statement


• Bu using a read statement

Assignment statement:

• A simple method of giving a value to a variable is by using assignment statement. The general
form of this is:
variableName = value ;

• For example:
total = 50 ;
gender = ‘M’;

• It is possible to assign single value to multiple variables by a single statement as shown below.
a = b = c = 0;

• All three variables are initialized with zero.

• It is possible to assign a value to a variable at the time of its declaration. The general form of this
is:
data type variableName = value ;

• For example:
int a=0;
char gender = ‘M’;

• The process of giving initial value to variable at the time of its declaration is known as the
initialization. The variables are not initialize at declaration are automatically initialized by its
default value.

• For example:
int a, b=5; //Here, variable ‘a’ is initialize with zero.
Read statement:

• To give a value to a variable from the keyboard is by using readLine() method of a


DataInputStream class.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 15


UNIT-I Introduction

• The following java program demonstrates that how to read a data from the keyboard.
//To print a square of a number.
import java.io.*;
public class square
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int a,b;
System.out.print("Enter any number: ");
a = Integer.parseInt(in.readLine());
b = a * a;
System.out.println("Square of a given number "+a+" is "+b);
}
}
Output:
Enter any number: 4
Square of a given number 4 is 16

• The readLine() is a method of DataInputStream class and is used to read the input from the
keyboard as a string. This value then converted into integer by using parseInt() method of Integer
class.

Getting values of variables:


There are two ways to display a value of a variable on the computer screen.

• By using print() method


• By using println() method
The basic difference between this two method is that print() method display the text on one line and
waits for displaying other information on same line, while println() method each time display text on a
new line.
For example,

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 16


UNIT-I Introduction

No. Statements Output


1. System.out.print(“Hello”); HelloJava
System.out.print(“Java”);
2. System.out.print(“Hello”); Hello
System.out.print(“\n”); Java
System.out.print(“Java”);
3. System.out.println(“Hello”); Hello
System.out.println(“Java”); Java
4. System.out.println(“Hello\nJava”); Hello
Java
5. System.out.println(“HelloJava”); HelloJava

The statement System.out.println() ; will print a blank line.

Scope of Variables:
Java variables have three categories.
1. Instance variable
2. Class variable
3. Local variable

Instance variable:

• Definition: A non-static variables declared in a class is known as instance variable. It is also


known as member variable.

• It is declared inside a class. It is created when the object of a class created. It takes different
values for each object. It is accessed by using object.
Example: class student
{
int s_no, s_marks ;
}

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 17


UNIT-I Introduction

• The class student contains two instance variables of integer data type, s_no and s_marks. The
following statement creates an object of the above class.
student s1 = new student();

• Now, the instances variables s_no and s_marks are used in a program by s1.s_no and s1.s_marks
respectively.
Class variable:

• Definition: A static variables declared in a class is known as class variable. It is also known as
static variable.

• It is global to a class and only one memory location is created for each class variable. It is used
when we want to have a variable common to all instance of a class. It is accessed by using name
of the class.
//Example of static variable.
//Write a Java program to count the number of object created in a program.
import java.io.*;
class square
{
static int count;
square()
{
count=count+1;
}
}
public class ObjectCount
{
public static void main(String[] args) throws IOException
{

square s1 = new square();


square s2 = new square();
square s3 = new square();
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 18
UNIT-I Introduction

System.out.println("Total number of object is: "+square.count);


}
}

Output:
Total number of object is: 3

• In above program, the variable ‘count’ is declared as a static variable in a class square. Each time
object of a class ‘square’ is created, its
Local variable:

• Definition: A variable declared and used inside a method is known as local variable.

• A variable declared inside a method is only visible to that method. Some variables are declared
in a program block that is defined between opening and closing curly brace. They are only
visible to that block only.
//Program for local variable.
class test
{
public static void square()
{
int a=5,b;
b=a*a;
System.out.println("Square :"+b);
}
public static void main(String args[])
{
square();
}
}

• In above java program, variables ‘a’ and ‘b’ both are local variables for a square function. These
two variables can not use in main() method otherwise it give an error.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 19


UNIT-I Introduction

Type casting:
• It is process to convert value of a variable from one data type to another. The general form of
type casting is
Data-type varibale1 = (data-type) variable2 ;
Example:
int m = 50;

• byte n = (byte) m ; In above example, the conversion is done from integer to byte. This is a
conversion from larger data type to smaller data type. There is possibility of data loss in the
conversion. This type of conversion is known as narrowing.
Automatic conversion

• Java does the conversion of one data type to another data type for some data types automatically
which is known as automatic conversion.
Example:
int m = 50;
long n = (long) m ;

• In above example, the conversion is done from integer to long. This is a conversion from smaller
data type to larger data type. There is no possibility of data loss in the conversion. This type of
conversion is known as widening or promotion.
Default values
In java, every variable has a default value. The following table shows default values for various data
types.
Type of variable Default value

Byte 0 (Zero)

short 0

Int 0

Long 0L

float 0.0f

double 0.0d

Char null character

boolean false

reference null

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 20


UNIT-I Introduction

Operators
"An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations”. Java operators can be classified into a number of categories. They include
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment and Decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Special Operator

1. Arithmetic Operator:
• Java provides all the basic arithmetic operators. These can operate on any built-in numeric data
type of Java. It can not operate on Boolean data type of Java. Java has both unary and binary
arithmetic operators. The arithmetic operators and their meaning are shown below:

Operator Meaning

+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division

• Integer Arithmetic: When both the operands in a single arithmetic expression (such as a + b)
are integers, the expression is called integer expression, and the operation is called integer
arithmetic. Integer arithmetic always results an integer value.
Example: If a & b are integer & its value is a = 14 and b=4 then we have the following
Results:
a -b results 10, a + b results 18; a*b results 56, a/b results 3 (decimal part truncated) and a
% b results 2 (remainder).

• Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic.
Example: If a, b and c are floats then we will have
a = 20.5, b=6.4
then a+b becomes 26.9, a-b becomes 14.1, a*b becomes 131.2 and a/b becomes 3.20313.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 21


UNIT-I Introduction

Java also support modulo division on float type variable. So, a%b becomes 1.3.

• Mixed-Mode Arithmetic: When one of the operand is real and the other is integer the
expression is called Mixed-mode arithmetic expression.
If either operand is of the real type, then only the real operation is performed and the result is
always a real number. Thus 15/10.0 gives 1.5 while 15/10 gives 1.

2. Relational Operator:
• A relation operator is used to make comparisons between two expressions.Java language
supports six relational operators. These operators and their meaning are shown below.

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

An expression containing a relational operator is termed as relational expressions. The value of


relational expression is either true or false.
Example:
A = 5;
B = 10;
The condition (A < B) evaluates as a True While (A==B) evaluates as a False.

3. Logical Operator:
Logical operators are useful in combining one or more conditions. Java language has the
following three logical operators.

Operator Meaning

&& Logical AND(True only if all conditions are true, otherwise false)

|| Logical OR(False only if all conditions are false, otherwise true)

! Logical NOT(True if exp. is false or vice - versa)

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 22


UNIT-I Introduction

Example on Logical AND:


A =5; B=10; X =10;
The condition (A < B && X == 10) evaluates true.
The condition (A < B && X!= 10) evaluates false.
The condition (A > B && X ==10) evaluates false.
The condition (A > B && X!= 10) evaluates false.
Example on Logical OR:
A =5; B =10; X = 10;
The condition (A < B || X ==10) evaluates true.
The condition (A < B || X != 10) evaluates true.
The condition (A > B || X ==10) evaluates true.
The condition (A > B || X != 10) evaluates false.
Example on Logical NOT:
The condition !(A <B) evaluates false and !( A> B )evaluates true

4. Assignment Operator(=):
• Assignment operators are used to assign the result of an expression to a variable. The general
form of assignment operator is
variable = expression;

• Java has a set of “Shorthand" assignment operators of the form


V op = exp ;

• Where V is a variable, exp is an expression and op is a binary arithmetic operator.

• The operator op= is known as the shorthand assignment operator.

• The assignment V op =exp; is equivalent to V = V op (exp);

• Example:
A += 1; same as A = A + 1;
B+= 1; same as B= B+ 1;
A += B + 3; same as A = A + (B + 3);

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 23


UNIT-I Introduction

A *= B; same as A = A * B;
A /= B; same as A = A / B;

• The use of shorthand assignment operator has three advantages:


o What appears on the left hand side need not be repeated and therefore it becomes easier
to write.
o The statement is more concise and easier to read.
o The statement is more efficient

5. Increment and Decrement Operator:


• The Java language uses two operators for incrementing and decrementing variables. These are
++ and -- operators are known as increment and decrement operator respectively.

• These operators increase or decrease the value of a variable by 1. The operator ++ adds 1 to the
operand and -- subtract 1 from the operand.

• They are used as prefix or postfix.

• Syntax:
Prefix Postfix
++VariableName VariableName++
--VariableName VariableName--

• When used a prefix, the value of a variable is incremented/ decremented before used in
expression. But when used as a postfix, its value is first used in expression and then the value is
incremented/ decremented.
Example:
[1] A=5 [2] int a = 0, b = 10:
A++ a = ++b; a = b++;
The value of a is 6. The value of a becomes 11 & The Value of a becomes10 and
b is 11. b is 11.
6. Conditional Operator
• It is also known as Ternary Operator.

• The general form of ternary operator is


exp 1 ? exp2 : exp3 ;

• Where exp1, exp2, exp3 are expressions.

• The operator ? : Works as follows :


SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 24
UNIT-I Introduction

exp1 is evaluated first.

• If it is non-zero (true), then the expression exp2 is evaluated and becomes the value of the
expression.

• If it is zero (false), then the expression exp3 is evaluated and becomes the value of the
expression.
Example: A = 10;
B = 15;
X = (A>B) ? A : B;

• In this example, X will be assigned the value of B. This can be achieved using the if...else
statements as follows.
if ( A > B)
X=A;
else
X = B;
7. Special Operator
• Java support some special operators such as
A. instanceof operator
B. dot operator

A. instanceof operator:

• The instanceof operator is an object reference operator and returns true if the object
on the left hand side is an instance of the class given on the right hand side. It is used
to check whether an object belongs to a particular class or not.
Example: person instanceof student

• is true if the object person belongs to the class student, otherwise it is false.
B. Dot operator:

• It is used to access the instance variable and method of class objects. It is also used to
access classes and sub-packages from a package.
Example:
person1.age //Reference to the variable age.
person1.salary() // Reference to the method salary.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 25


UNIT-I Introduction

Decision making

Introduction
When a program breaks the sequential flow and jumps to another part of the block, it is called
branching. When the branching is based on a particular condition, it is known as conditional
branching. If branching takes place without decision, it is known as unconditional branching.
Branching statement:
It alters (changes) sequential execution of program statements. They are
1. if statement
1.1 if statement
1.2 if…else statement
1.3 Nested if…else statement
1.4 Else if ladder
2. switch statement

1.1. if statement:
It is decision making statement. It is used to control the sequence of the execution of statements.
Syntax:
if ( condition )
{
Statement-1;
}
Description: Initially condition is evaluated. Statement-1 is executed only if condition is true.
Example:
import java.io.*;
class t
{
public static void main(String args[]) throws IOException
{
int age;
BufferedReader in=new BufferedReader (new InputStreamReader(System.in));

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 26


UNIT-I Introduction

System.out.print("Enter your age : ") ;


age=Integer.parseInt(in.readLine()) ;
if ( age < 0 )
System.out.println("Negative age given") ;
if ( age > 0 )
System.out.println("Your age is :" +age) ;
}
}
Input & Output:
Enter your age : 25
Your age is 25

1.2. if…else statement:


Syntax:
if ( condition )
{
Statement-1;
}
else
{
Statement-2;
}
Each statement may be a single statement or a compound statement enclosed in curly braces (Block).
The condition is any expression that returns a Boolean value either true or false. The else part is
optional.
Description: Initially condition is evaluated. If condition is true then statement-1 is executed, otherwise
statement-2 is executed.
There is no such condition when both the statements are executed.
Example: Write a Java program to find maximum number from the given two integer numbers.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 27


UNIT-I Introduction

import java.io.*;
class t
{
public static void main(String args[]) throws IOException
{
int a, b;
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
System.out.print("Enter a : ") ;
a=Integer.parseInt(in.readLine()) ;
System.out.print("Enter b : ") ;
b=Integer.parseInt(in.readLine()) ;
if ( a > b )
System.out.println("Given number a="+a+" is maximum") ;
else
System.out.println("Given number b="+b+" is maximum") ;
}
}
Output:
Enter a : 54
Enter b : 25
Given number a = 54 is maximum

1.3. Nested if…else statement: one if…else statement written inside another if…else statement is
known as nested if ... else statement.
Syntax:
if ( condition-1 )
{
if ( condition-2)

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 28


UNIT-I Introduction

{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
next_statement ;
Description:
Initially condition-1 is evaluated.

• If condition-1 is true then it tests the condtion-2. If the condition-2 is true then statement-1 is
executed otherwise statement-2 is executed. The control passes to the next_statement following
the if…else statement.
• If the condition-1 is false then statement-3 will be executed.

Example: Write a Java program to read a number and check whether it is zero or positive or negative
number using nested if…else statement.
import java.io.*;
public class NestedIf
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a:");
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 29
UNIT-I Introduction

a=Integer.parseInt(in.readLine());
if ( a>=0 )
if( a>0 )
System.out.println("a="+a+" is Positive.");
else
System.out.println("a="+a+" is Zero.");
else
System.out.println("a="+a+" is Negative.");
}
}
Output:
Enter a : 10
a = 10 is Positive.

1.4. Else if ladder:


It is based on a sequence of if statements under an else part. The following gives the syntax of else if
ladder.
Syntax:
if ( condition-1 )
{
Statement-1;
}
else if ( condition-2 )
{
Statement-2;
}
else if ( condition-3 )
{

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 30


UNIT-I Introduction

Statement-3;
}
else
{
Statement;
}
Description:
Initially the condition-1 is tested.

• If it is true then statement-1 is executed.


• If it is false then the condition-2 is tested. If it is true then stamen-2 is executed otherwise it
check the condition-3 and so on.
If none of the condition is true then the final else statement will be executed.
If there is no final else and all other condition are false then no action will take place.

Example: Write a java program to read a number and print its corresponding color name using
following data using else if ladder.
Color code Name of a color
1 Red
2 Green
3 Blue
4 Black
import java.io.*;
public class ElseIfLadder
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a color code:");

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 31


UNIT-I Introduction

a=Integer.parseInt(in.readLine());
if ( a= =1 )
System.out.println("Red color");
else if ( a= =2 )
System.out.println("Green color");
else if ( a= =3 )
System.out.println(" Blue color");
else
System.out.println("Black color");
}
}
Output:
Enter a color code : 3
Blue color

2. switch statement:
It is a multi-way decision making statement the allows choosing of a statement ( or a group of
statements) among several alternatives.
Syntax:
switch ( expression )
{
case value1 : statement1;
break;
case value2 : statement2;
break;
:
:
default : statement;

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 32


UNIT-I Introduction

}
Next_statement ;
Description: Initially expression is solved. Control transfer to the statements following the case whose
value is equal to the value of the expression. The default part is optional in switch statement.

Example: Write a java program to read a number and print its corresponding color name using
following data using switch statement.
Color code Name of a color
1 Red
2 Green
3 Blue

import java.io.*;
public class Switch1
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a color code:");
a=Integer.parseInt(in.readLine());
switch( a )
{
case 1 : System.out.println("Red color"); break;
case 2 : System.out.println("Green color"); break;
case 3 : System.out.println("Blue color"); break;
default : System.out.println("Wrong choice.");
}
}
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 33
UNIT-I Introduction

}
Output:
Enter a color code : 3
Blue color

Looping statements:
It is also known as Iteration statements. There are three looping statements in Java.
They are
1. while loop
2. do…while loop
3. for loop

1. while loop: It is also known as entry-control loop. It is looping statement.


Syntax:
while ( condition )
{
body of loop
}
next_statement ;

The condition can be any Boolean expression. The body of loop will be executed as long as the
condition is true.
Description: Initially condition is tested.

• If the condition is true then the body of loop is executed and the execution continues as long
as it remains true.
• If the condition is false then loop is terminated and next_statement is executed.

Example: Write a Java program to display 1 to N number using while loop.


//To print 1,2,3,....N using while loop
import java.io.*;
public class while1
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 34
UNIT-I Introduction

{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int i, n;
System.out.print("Enter any positive number:");
n = Integer.parseInt(in.readLine());
i=1;
while(i<=n)
{
System.out.print(i+", ");
i=i+1;
}
}
}
Output:
Enter any positive number: 3
1, 2, 3,

2. do… while:
Syntax:
do
{
body of loop
} while ( condition ) ;
next_statement ;

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 35


UNIT-I Introduction

Description: Initially body of loop is executed and then condition is evaluated. The body of loop is
executed as long as the condition remains true. The loop is terminating when condition becomes false.

Example: Write a Java program to display 1 to N number using do…while loop.


//To print 1,2,3,....N using do...while loop
import java.io.*;
public class dowhile1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int i,n;
System.out.print("Enter any positive number:");
n = Integer.parseInt(in.readLine());
i=1;
do
{
System.out.print(i+", ");
i=i+1;
}while(i<=n);
}
}
Output:
Enter any positive number: 3
1, 2, 3,

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 36


UNIT-I Introduction

3. for loop:
The for loop is useful while executing a statement a fixed number of times.
Syntax:
for(initialization ; condition ; updation)
{
body of loop
}
next_statement ;

Description: The initialization part is executed only once. Next the condition is evaluated.

• If the condition is false then the next statement after for loop is executed.

• If the condition is true then after executing the body of loop and then update part is executed.
The condition is evaluated once again and the whole process is repeated as long as the condition
is true.
Example: Write a Java program to display 1 to N number using for loop.
//To print 1,2,3,....N using for loop
import java.io.*;
public class for1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int i,n;
System.out.print("Enter any positive number :");
n = Integer.parseInt(in.readLine());
for( i=1 ; i<=n ; i++ ) System.out.print(i+", ");
}
}

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 37


UNIT-I Introduction

Output:
Enter any positive number : 3
1, 2, 3,

Jumps in Loop:
Sometime, when executing a loop it becomes desirable to leave the loop or skip a part of the loop. This
will be done by jumping statement in the loop.
There are two ways to jump in a loop.
1. Jumping out of a loop ( break statement)
2. Skipping a part of a loop ( continue statement )

1. break statement:
Syntax:
break ;
Description: A break statement terminates the execution of loop and the control is transferred to the
statement immediately following the loop.
A break statement is very useful in switch statement.

Example: Write a Java program to display square of the given number and use 0(zero) for exit.
import java.io.*;
public class break1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int n;
while(true)
{
System.out.print("Enter any number :");

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 38


UNIT-I Introduction

n = Integer.parseInt(in.readLine());
if (n= =0 ) break;
System.out.println("Square of "+n+" is "+n*n);
}
}
}
Output:
Enter any number : 3
Square of 3 is 9
Enter any number : 7
Square of 7 is 49
Enter any number : 0

2. continue statement:
Syntax:
continue ;
Description: A continue statement skips the remaining statement in the loop and control transfer to the
condition.
Example: Write a Java program to display sum of only positive numbers.
import java.io.*;
public class continue1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int n,s=0;
while(true)
{

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 39


UNIT-I Introduction

System.out.print("Enter any number…0 for exit :");


n = Integer.parseInt(in.readLine());
if (n<0 ) continue;
if (n==0 ) break;
s=s+n;
}
System.out.print("Sum="+s);
}
}
Output:
Enter any number…0 for exit : 20
Enter any number…0 for exit : 10
Enter any number…0 for exit : -7
Enter any number…0 for exit : 30
Enter any number…0 for exit : 0
Sum = 60

Arrays:
• An array is collection of same data type that is referred by a common name.
• An array is a group of like-typed variables that are referred to by a common name.
• Arraysof any type can be created and may have one or more dimensions.
• A specific elementin an array is accessed by its index.
• Arrays offer a convenient means of groupingrelated information.

Types of an array:
It can be

• One-dimensional array
• Two-dimensional array
• Multi-dimensional array

One-dimensional array:
Creating a one-dimensional array:

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 40


UNIT-I Introduction

A one dimensional array is created involves three steps:

• Declare the array


• Create a memory location
• Putting values into the memory location

Declare the array:


An array in Java can be declared by two ways:
Syntax:
datatype arrayname [ ] ;
OR
datatype [ ] arrayname ;
Here, datatype is any fundamental datatype of Java such as int, char, float etc. arrayname is a
valid identifier that gives name of an array.
Example:
int age [ ] ; OR int [ ] age;
This statement declares an array age with the integer datatype. The square brachets in declaration is
empty. An array age does not contain any values.
Create a memory location:
The new operator is used to create a memory for an array.
Syntax:
Arrayname = new datatype [ size ] ;
Here, arrayname is a valid identifier that gives name of an array. datatype is any fundamental
datatype of Java such as int, char, float etc. Size is total number of elements in the array. The elements in
the array memory allocated by new will be automatically initialized to zero.
Example:
age = new int[ 50 ] ;
Now, this array age will refer to an integer array of 50 elements. All the elements in the will be
initialized to zero.
It is possible to declare and create a memory for an array into a single line as shown below.
int age [ ] ;
age = new int[ 50 ] ;

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 41


UNIT-I Introduction

This two line can be write into a single line as


int age [ ] = new age [ 50 ] ;

Initialization of an array:
An array can be initialized when they are declared.
Syntax:
datatype arrayname [ ] = {List of values separated by comma} ;
Here, datatype is any fundamental datatype of Java such as int, char, float etc. arrayname is a
valid identifier that gives name of an array.
There is no need to write size of an array. There is no need to use new operator.
Example:
int age[ ] = {10, 20, 30, 40, 50};
Here, size of an array is 5. A value of age[0] is 10, age[1] is 20 and so on.If you try to access
elements outside the range of the array, you will cause a run-time error.

Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle
differences. To declare a multidimensional array variable, specify each additional index using mother set
of square brackets. For example, the following declares a two-dimensional array variable called twoD.
Example:
int twoD[][] = new int[4][5];
The following program numbers each element in the array from left to right, top tobottom, and then
displays these values:
Example:
// Demonstrate a two-dimensional array.
class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 42
UNIT-I Introduction

for(i=0; i<4; i++)


{
for(j=0; j<5; j++)
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
{
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify thememory for the
first (leftmost) dimension. You can allocate the remaining dimensions separately. For example, this
following code allocates memory for the first dimension oftwoD when it is declared. It allocates the
second dimension manually.

SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 43

You might also like