0% found this document useful (0 votes)
38 views11 pages

2nd BSC (OOP With Java)

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

2nd BSC (OOP With Java)

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

nd

2 BSC / SEM- III Object Oriented Programming with Java Page 1


UNIT – I
JAVA HISTORY
Java is an object oriented programming language (OOP) developed by James Gosling and his team
members in 1991 at Sun Microsystems, USA. At first, Java is called Oak. Java is developed on C and C++
but removes most of the features from C and C++ and adds his own features. It is designed for the
development of software for electronic devices like TVS, VCR etc.

STRUCTURE OF JAVA PROGRAM


Documentation Section
Import Statement
Package Statement
Interface Statement
Class definitions
main()
{
fields declaration;
Methods declarations
}

Documentation Section:
 This section contains set of comment lines like name of the program, author name, date of creation and
some other details.
 We can include comments begin with // (or) begins with /* and ends with*/.

Import Statement:
 This statement is similar to #include statement in „C‟ language.
Eg1: import java.io.*;
Eg2: import java.io.System;
 In the above example, we can load all the classes or single class in the io package.

Package Statement:
 This statement declares a package name and informs the compiler that the classes defined here are
belongs to this package.

Interface Statement:
 An interface is a class but includes a group of methods declaration.
 This is used only when we implement the concept of multiple inheritance in the program.

Class Definitions:
 A Java program contains multiple class definitions. Classes are the essential part in the program.

Main Method:
 Main method is the essential part in the java program. A simple program may contain only this part.
 In the main method, we can create objects of various classes.

Prepared By Ranjith Reddy, Srivema Degree College


nd
2 BSC / SEM- III Object Oriented Programming with Java Page 2
IMPLEMENTING A JAVA PROGRAM
To implement a java program we have to follow three steps.
 Creating a program
 Compiling a program
 Running a program

Creating a program:
We can create a program by using any text editor.
Eg: import java.io.*;
class Test
{
Public static void main(String args[])
{
System.out.println(“Hello”);
}
}
We must save this program as Test.java i.e. the filename contains the class name. This file is
called as source code.

Compiling a program:
 To compile the program, we must run the java compiler javac with the name of the source code on the
command prompt.
Eg: javac Test.java
 If there is no errors, then the compiler creates a file called as Test.class. This file is called as byte
code.

Running a program:
To run the program we must run the java interpreter java with the name of the source code on the
command prompt.
Eg: java Test
Now the interpreter looks for the main method and begins the execution from there. After compiling
the execution of the program, it displays the following output on the screen.
Hello

JAVA VIRTUAL MACHINE (JVM)

Source Code  .java file

Java Compiler

Byte Code  .class file

Interpreter

Machine Code

 The java compiler javac translates the source code file into byte code file. This byte code file is also
called as virtual machine code.
 The java interpreter java translates the byte code file into machine code file.
Prepared By Ranjith Reddy, Srivema Degree College
nd
2 BSC / SEM- III Object Oriented Programming with Java Page 3
JAVA TOKENS
The smallest individual units in a program are called as tokens. Java supports 5 types of tokens. They
are
 Keywords (or) Reserved words
 Identifiers
 Constants (or) Literals
 Operators
 Separators

Keywords:
A keyword is a group of characters that has fixed meaning and this meaning cannot be changed. The
keywords cannot be used as variable names. All keywords must be written in lowercases. The keywords are
also called as reserved words. Java language has 50 keywords. Some of them are int, if, switch, break,
continue etc.

Identifiers:
User-defined words such as variables, function names, array names are called identifiers. These
identifiers consist of alphabets, digits and an underscore.
Rules:
1. The first character should be an alphabet and the remaining characters are alphabets or digits or
underscore.
2. The length should be any number of characters but the compiler looks first 8 characters only.
3. Lowercase and uppercase letters are different.
4. Keywords cannot be used as identifiers.
5. Special characters and blank spaces are not included.
Eg: Valid variables : b, sal, emp_no, a105 etc
Invalid variables : x+y, 7asd, char etc

Constants:
Constants are fixed values that do not change during the execution of a program. Java supports four
types of constants. They are
Integer Constants: An integer constant consists of either +ve or –ve values, but not allows decimal part.
Eg: 67, -89 etc.
Float Constants: Float constant consists of either +ve or –ve values, but allows decimal part. „f‟ or „F‟ must
be appended at the last of the float value.
Eg: 12.35f, -56.76f etc.
Character Constants: Character constant consists of either single character or single digit or single symbol
must be enclosed within the single quotations.
Eg: „s‟, „9‟, „+‟ etc.
String Constants: String constant consists of group of characters must be enclosed within the double
quotations.
Eg: “New York”.

Operators:
An operator is a symbol that takes one or more operands and performs some calculations on them.
Some operators are arithmetic operators, relational operators, logical operators etc.
Prepared By Ranjith Reddy, Srivema Degree College
nd
2 BSC / SEM- III Object Oriented Programming with Java Page 4
Separators:
Separators are symbols which are used to indicate the group of code is divided or combined. The
separators are
 Parenthesis ()
 Braces {}
 Brackets []
 Semicolon ;
 Comma ,
 Period .

DATA TYPES
The type of data that the variables hold in a programming language is called data type. Java supports
two types of data types.
Data Types
Tokens

Primitive Non-Primitive
(Or) (Or)
Built-in Derived

Numerical Non-Numerical Arrays

Integer Float Char Boolean Classes

Integer:
The keyword int is used to store either +ve or –ve values, but not allows decimal part. It occupies
the memory 4 bytes.
Eg: 35, -27 etc.
Data Type Range Size
byte -128 to 127 1 byte
short -32,768 to 32,767 2 bytes
int -2,147,483,648 to -2,147,483,647 4 bytes

Float:
The keyword float is used to store either +ve or –ve values, but allows decimal part. It occupies the
memory 8 bytes. „f‟ or „F‟ must be appended at the end of the float value.
Eg: 65.12f, -34.56f etc.

Char:
The keyword char is used to store either single character or single digit or single symbol must be
enclosed with single quotations. It occupies the memory 2 bytes.
Eg: „s‟, „5‟, „&‟ etc

Boolean:
The keyword boolean is used to store either „True‟ or „False‟ values. It occupies the memory 1 bit.
Eg: T or F
Prepared By Ranjith Reddy, Srivema Degree College
nd
2 BSC / SEM- III Object Oriented Programming with Java Page 5
VARIABLES
A variable is defined as a meaningful name which is used to store the value. A variable may take
different values at different places during execution of a program. Java allows the declaration of a variable
anywhere in the program.

Rules:
1. The first character should be an alphabet and the remaining characters are alphabets, digits or
underscore.
2. The length should be any number of characters but java compiler looks first 8 characters only.
3. Lowercase and uppercase letters are different.
4. Keywords cannot be used as identifiers.
5. Special characters and blank spaces are not included.
Eg: Valid variables : b, sal, emp_no, a105 etc
Invalid variables : x+y, 7asd, char etc

Declaration of variables:
Each variable must be declared before used in the program. The declaration consists of data type
followed by one or more variables and end with a semicolon.
Syn: datatype var1, var2, …varn;
Eg: int a,b,c;
In the above example, int is a keyword, a,b,c are variable names separated by commas.

Giving values to the variables:


Values can be assigned to variables by using two methods. They are
a) By using assignment operator
b) By using readLine() method
a) By using assignment operator: A simple way of giving values to variables is the assignment operator.
Syn: variable = value;
Eg: a=10;
b) By using readLine() method: We can also give values to the variables by using readLine() method.
This method used to read the input from the keyboard as a string which is converted to corresponding
data type by using wrapper classes.

TYPE CASTING
The process of converting one data type into another data type is called as type casting. We
frequently do this process when we need to store a value of one type into a variable of another type. When
the value of a higher data type is converted to lower data type, some data is lost.
Syn: variable = (data type) variable;
Eg: float a = 12.75f;
int b;
b = (int)a; returns 12
So to avoid such type of wrong results, we always convert lower data type to higher data type.
Eg: int a = 10;
float b;
b = (float)a; returns 10.0

Prepared By Ranjith Reddy, Srivema Degree College


nd
2 BSC / SEM- III Object Oriented Programming with Java Page 6
Program
import java.io.*;
class Typecasting
{
public static void main(String args[])
throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter s1,s2,s3 values:”);
int s1=Integer.parseInt(br.readLine());
int s2=Integer.parseInt(br.readLine());
int s3=Integer.parseInt(br.readLine());
int tot=s1+s2+s3;
float avg=(float)tot/3;
System.out.println(“tot=”+tot+”\n”+”avg=”+avg);
}
}
Input:
Enter s1,s2,s3 values:
40
60
51
Output:
tot=151
avg=50.33

SYMBOLIC CONSTANTS
Syn: final datatype variable=value;
 To declare a symbolic constant, the keyword final is placed before the normal variable declaration and
assigns it a value.
 Symbolic names follow the same rules of variable names, but they are written in capital letters to make
the difference from normal variable.
 After declaration of symbolic constants, the value does not change during execution of the program.
 In C and C++ symbolic constants are declared by using #define statement.
Eg: import java.io.*;
class Area
{
public static void main(String args[])
{
final float PIE=3.14f;
float r=2.0f;
float area=PIE*r*r;
System.out.println(“Area=”+area);
}
}
Output:
Area=12.56
Prepared By Ranjith Reddy, Srivema Degree College
nd
2 BSC / SEM- III Object Oriented Programming with Java Page 7
COMMAND LINE ARGUMENTS
 Command line arguments are parameters that are supplied to the program at the time of execution.
 Java programs can receive and use the parameters provided in the command line.
 The parameters provided in the command line are passed to the array args[] as its elements.
Eg: java Test C C++ Java
 In the above example, we have three parameters. These are assigned to the array as follows:
C  args[0]
C++  args[1]
Java  args[2]

Program
import java.io.*;
class Cmdline
{
public static void main(String args[])
{
int count,i=0;
count=args.length;
System.out.println(“No. of arguments=”+count);

while(i<count)
{
System.out.println(args[i]);
i++;
}
}
}
Output:
No. of arguments=3
C
C++
Java

OPERATORS
An operator is a symbol that takes one or more operands and performs some calculations on them.
Java supports mainly eight types of operators. They are
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operator
 Unary operators
 Conditional operator
 Bitwise operator
 Special operators

Prepared By Ranjith Reddy, Srivema Degree College


nd
2 BSC / SEM- III Object Oriented Programming with Java Page 8
Arithmetic Operators:
Arithmetic operators are used to perform mathematical calculations. Let us consider two variables
declared as
int a=9, b=7;

Operator Meaning Example


+ Addition a + b = 16
- Subtraction a–b=2
* Multiply a * b = 63
/ Divide a/b=1
% Modulus a%b=2

In the above table a and b are called operands. The addition, subtraction and multiplication (+, -, and
*) operators perform the normal arithmetic operations in java programs.
The division (/) operator returns the quotient value. If both operands are integers, then the result will
be an integer. If one or more operands are float, then the result will be float.
Eg: 9 / 7 = 1 9.0 / 7 = 1.285714 9.0 / 7.0 = 1.285714
The modulus (%) operator returns the remainder value of an integer division.
Eg: 9 % 7 = 2
Note: If an arithmetic expression consists of lot of operators then *,/,% will be performed first in a left to
right order before any addition or subtraction could be performed.
Eg: 3 + 4 * 7 = 31 (not 49)

Relational Operators:
Relational operators are used to compare two values. These operators return either 1 (TRUE) or 0
(FALSE) values. Let us consider two variables declared as
int a=9, b=7;

Operator Meaning Example


< Less than 9<7=0
<= Less than or equal to 9 <= 7 = 0
> Greater than 9>7=1
>= Greater than or equal to 9 >= 7 = 1
== Equal to 9==7=0
!= Not equal to 9 != 7 = 1

If an arithmetic expression consists of a relational operator, then the arithmetic expression will be
evaluated first and then the result will be compared. Because arithmetic operators have a higher priority than
relational operators.
Eg: 7 + 5 < 8 + 2 gives 0 (FALSE)

Logical Operators:
Logical operators are used to combine two or more relational expressions. Java supports three logical
operators. They are logical AND(&&), logical OR(||) and logical NOT(!).

Prepared By Ranjith Reddy, Srivema Degree College


nd
2 BSC / SEM- III Object Oriented Programming with Java Page 9
Logical AND:
If both the expressions of the logical AND are true then it returns true, otherwise false. The truth
table of logical AND is:
A B A&&B
1 1 1
1 0 0
0 1 0
0 0 0
Eg: (2 <= 3) && (3 != 4)  1(True)
Logical OR:
If one of the expression of the logical OR is true then it returns true, otherwise false. The truth table
of logical OR is:
A B A||B
1 1 1
1 0 1
0 1 1
0 0 0
Eg: (2 < 3) || (3 != 3)  1(True)
Logical NOT:
The logical NOT operator takes a single expression. If the expression of the logical NOT is true then
it returns false. If the expression of the logical NOT is false, then it returns true. The truth table of logical
NOT is:
A !A
1 0
0 1
Eg: !(3 < 4)  !(True)  False

Assignment Operator:
Assignment operator (=) is used to assigning the values to the variables. The assignment operator
has right-to-left associativity. The syntax is:
Syn: variable = value (or) variable (or) expression;
Eg: a = 10;
b = a;
c = a * b;
In the above example, the expression on the right side of the = sign is evaluated and assigns the result
to the variable. Another syntax of assignment operator is:
Syn: variable op = expression; where op is an arithmetic operator.
Eg: a + = 10 * 2; is equal to a = a + 10 * 2;

Unary Operators:
Unary operators perform on single operand. Java supports two unary operators. They are increment
and decrement operators.
Increment (++) and Decrement (--) Operators:
The increment operator increases the value by 1. Similarly decrement operator decreases the value
by 1.

Prepared By Ranjith Reddy, Srivema Degree College


nd
2 BSC / SEM- III Object Oriented Programming with Java Page 10
The increment/decrement operators have two variants. Namely, prefix and postfix. In a prefix
expression (++x), the value of x is incremented first and it is assigned. Whereas in a postfix expression
(x++), the value of x is assigned first and it is incremented.
Eg: int x = 10,y; Eg: int x = 10,y;
y = ++x; y = x++;
y = 11 and x = 11 y = 10 and x = 11
The same principle applies to decrement operator.

Conditional Operator:
The conditional operator (?:) is also called as ternary operator. The syntax is:
Syn: variable = exp1 ? exp2 : exp3;
In the above syntax, the exp1 must be a relational expression. The exp1 is evaluated first. If it is
true, then exp2 is executed, otherwise exp3 is executed.
Eg: int a = 5 , b = 3 , c;
c = (a < b) ? (a+b) : (a-b); therefore c = 2

Bitwise Operators:
Bitwise operators perform operations at the bit level. The bitwise operators expect their operands to
be integers and treat them as a group of bits. Java supports 6 types of bitwise operators. They are
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise EXCLUSIVE OR
! Bitwise NOT
<< Bitwise left shift
>> Bitwise right shift
Special Operators
Java supports two types of special operators. They are
a) instanceof
b) Dot (.) operator

a) instanceof: This operator is an object reference operator. If the object on the left hand side belongs to the
class on the right hand side, then it returns true.
Eg: if(br instanceof A)
In the above example, br is an object name and A is class name. If the br belongs to the class A, it
returns true. Otherwise it is false.
b) Dot (.) operator: This operator is used to access the members and methods of a class.
Eg: s.sno=101;
s.getdata();

Prepared By Ranjith Reddy, Srivema Degree College


nd
2 BSC / SEM- III Object Oriented Programming with Java Page 11
PROGRAMMING EXAMPLES
Program Write a java program to find addition of two integers.
import java.io.*;
class Add
{
public static void main(String args[])
{
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println("c="+c);
}
}
Output:
c=30

Program Write a java program to find addition of two integers by using readLine() method.
import java.io.*;
class Sum
{
public static void main(String args[])
throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c;
System.out.println("Enter a and b values:");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println("c="+c);
}
}
Input:
Enter a and b values:
10
20
Output:
c=30

Prepared By Ranjith Reddy, Srivema Degree College

You might also like