0% found this document useful (0 votes)
27 views34 pages

BCA-2 Java Unit-1 & Unit-2 Notes

Uploaded by

nagesh_salla
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)
27 views34 pages

BCA-2 Java Unit-1 & Unit-2 Notes

Uploaded by

nagesh_salla
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/ 34

Programming in Java Prepared by S.

Nagesh MCA NET

UNIT – I
CHAPTER – I
INTRODUCTION TO JAVA
1. History of Java
Java is a purely object oriented programming language developed from Sun
Microsystems in 1991 by team headed by James Gosling.
Java was initially developed for the electrical home appliances like remote control,
washing machines refrigerators etc.
In 1990, Sun Microsystems got a project called Green project to develop embedded
software for home appliances. Sun Microsystems formed a team headed by James Gosling.
The team concluded that existing programming languages were in adequate for this project
due to their machine dependence.
In 1991, the team developed a platform independent language by extending and
modifying C++ language and named as “Oak”. Later this programming language was
renamed as “Java” due to copy right problems.
Here's a more detailed timeline:
 1991: The Green Project at Sun Microsystems, led by James Gosling, begins with the
goal of creating a language for consumer electronics.
 1992: The initial prototype, named Oak, is developed.
 1994: The team shifts focus to the internet and the language is renamed Java.
 1995: Java is officially launched by Sun Microsystems.
 1996: The first Java Development Kit (JDK 1.0) is released.
 2009: Oracle acquired Sun Microsystems, taking ownership of Java.
2. Java Features
Java provides various features. The main features are as follows.
 Simple: Java is a simple language. Java was designed to be easy for the professional
programmer to learn and effectively.
 Object Oriented: Java is purely object oriented language. Everything in Java are defined
inside of a class and accessed through object. Main () method is defined inside of a class.
 Both compiled and interpreter: Java combines both compiler and interpreter. Java
compiler translates source code into byte code instructions. Java interpreter generates a
machine code that can be directly executable by the machine.
 Platform independence and portable: Java programs can be easily moved from one
computer system to another computer, anywhere and anytime. Changes and upgrades
in operating system, processer and system recourses not force any changes in Java
program. Java ensures portability because Java compiler generates byte code
instructions that can be run on any machine.
 Distributed: Java is designed as distributed environment of internet. It has the ability to
share both data and programs. This enables multiple programs at multiple remote
locations to work together.
B.Sc - V SEM - Computer Science 1
Programming in Java Prepared by S. Nagesh MCA NET

 Secure: Java provides security from viruses and unknown program by providing
firewall between a networked applications and user local computer.
 Robust: Java provides strict compile time and runtime checking and eliminates
situations that are error prone.
 RMI: Remote Method Invocation allows application to call object located at remote site
and communicate with them.
 Memory Management: Java uses Garbage collector to destroy memory of unused
objects.
 Multithreaded: Multithreaded means handling multiple tasks simultaneously. Java
supports the multithreaded programming which allows writing a program that does
many things simultaneously.

3. How Java differ from C & C++


Differences between Java and C
 Java is an objected oriented programming languages whereas ‘C’ is procedure
Oriented Programming Language
 Java compiler generates byte code file that can run anywhere where as C compiler
generates object code that is machine dependent.
 Java does not support data types struct and union, where as ‘C’ uses to create user
defined data types.
 Java does not support sizeof() operator where C supports sizeof() operator to get size
of a variable.
 Java does not support pointers where as ‘C” uses pointers to store address of
variable.
 Java uses to import keyword where ‘C’ uses preprocessor #include to corporate
predefined code.
Differences between Java and C++
 Java is a true objected oriented programming languages whereas ‘C++’ is basically
with extension of object based Oriented,
 Java does not support multiple inheritance. This can be implemented by interface
 Java does not support copy constructor
 Java does not support operator overloading
 Java replaced destructor with finalize() method that executes automatically when
object going to be destroyed.
 Java automatically destroy memory of unused object by Garbage collector, but C++
uses delete keyword to destroy memory.
4. JDK & JRE
Java Development Kit:
The JDK is a software development kit that provides all the necessary tools and
resources to develop, compile, debug, and run Java applications. The main tools are as
follows:
 javac (Java Compiler): It is a java compiler which translates Java source code
(.java files) into Java bytecode (.class). It takes name of the java source file as input.
 java: java is an interpreter which runs java programs by interpreting byte code. It
generates machine code and runs on machine directly. It takes name of the main
class as input

B.Sc - V SEM - Computer Science 2


Programming in Java Prepared by S. Nagesh MCA NET

 appletviewer: It is used to run Java applet program without using web browser
 jdb (Java debugger): Java debugger helps in finding and the fixing of bugs in Java
language programs.
 javadoc: This tool is used to generate API documentation into HTML format from
Java source code. It is interesting to know that Javadoc is the industry standard for
documenting Java classes.
 javap: It is used to display the content of the predefined packages of java.
Java Runtime Environment (JRE):
The JRE is a software package that provides the essential components
required to run compiled Java applications. It is intended for end-users who only
need to execute Java programs, not develop them. The JRE includes:
 Java Virtual Machine (JVM): JVM is responsible for executing Java bytecode. The
JVM acts as an abstract machine that interprets the bytecode and translates it into
platform-specific machine instructions.
 Java Class Libraries: A rich set of pre-written classes and APIs (Application
Programming Interface) that provide fundamental functionalities like
input/output, networking, data structures, and graphical user interface (GUI)
components.
5. Java Primitive Types
Data types specify type of values assigned to a variable. Data types also specify
storage area allocated to a variable. In Java, data types are classified as follows.

Data type

Primitive Non-Primitive

Numeric Non-Numeric Array


Class
Interface
Integer Floating point Character Boolean

byte float char boolean


short double
int
long

Integer Type:
Integer type represents whole numbers. There are four integer types as given below.
Type size min max
byte 1 byte -27 27-1
short 2 bytes -2 15 215-1
int 4 bytes -231 231-1
long 8 bytes -263 263-1

B.Sc - V SEM - Computer Science 3


Programming in Java Prepared by S. Nagesh MCA NET

Floating Type:
Floating point types are used to represent real numbers. There are two floating types
as given below.
Type size min max
float 4 bytes -3.4e-38 3.4e+38
double 8 bytes -1.7e-308 1.7e+308
In Java, the default floating type is double.
Character Type:
Character type represents a single character values enclosed in single quotes. Java
supports a data type char to represent character type. It reserves two bytes of memory. Java
supports Universal code.
Boolean:
Java supports this data type to represent two possible values true or false.
6. CREATING AND EXECUTION OF JAVA PROGRAM
A Java program is a collection of classes, each class consist fields and methods. Every
Java program consists at least one class which defines one method known as main()
method.
Let us create a simple example Java program.

class Example
{
public static void main( String ar[ ])
{
System.out.println(“Hello World”);
}
}
Creating a Java Program:
A Java source program can be created using any text editor.
 Open any text editor such as Notepad
 Enter the source code
 Save the source code with the name of main class name with java extension. The above
program has to be saved with file name “Example.java”

Compiling Java Program


The Java Compiler compiles the java source code and translates into byte code. The
byte code files have file name as class name and have a file extension of .class. Java
programs are compiled from DOS (Disk Operating System) command prompt.
 Open DOS commend prompt
 Move to the folder that contains the our Java program using cd command.
 Compile the program using javac tool. If the Java source code is free from errors,
compiler creates byte code file with name of class name and .class as file extension.
B.Sc - V SEM - Computer Science 4
Programming in Java Prepared by S. Nagesh MCA NET

Syntax: C:\> javac filename


Ex: C:\> javac Example.java
Here byte code file will be created with name of Example.class

Running Java program


The Java program can be run using java interpreter tool from DOS command
prompt. The java interpreter interprets byte code and generates machine specific code and
directly executes on processor. It does not generate any file.
Syntax:
C:\> java mainclassname
Ex:
C:\> java Example
7. Basic Java Operators
Operator is a symbol that is used to perform basic mathematical and logical
operations on its operands. In an expression a+b, a & b are operands and ‘+’ is a operator.
Java supports different types of operators.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic Operators: Arithmetic operators are used to perform basic mathematical operations.
There are five arithmetic operators as given below.
Operator meaning Description
+ Addition if a=13, b = 8 then a+b gives 21
- Subtraction if a=13 , b = 8 then a-b gives 5
* Multiplication if a=13 , b = 8 then a*b gives 104
/ Division (Quotient) if a=13 , b = 8 then a/b gives 1
% Module (Reminder) if a=13 , b = 8 then a%b gives 5
Relational Operators: The relational operators are used to compare two values. These operators
are used to construe Boolean expression. The result of the Boolean expression is either true (1) or
false (0).
Operator meaning Description
< is less than if a=15, b=4 then a<b gives false
<= is less than or equal to if a=15, b=4 then a<=b gives false
> is greater than if a=15, b=4 then a>b gives true
>= is greater than or equal to if a=15, b=4 then a>=b gives true
== is equal to if a=15, b=4 then a==b gives false
!= is not equal to if a=15, b=4 then a!=b gives true

Logical Operators: The logical operators are used to combine two or more Boolean expressions.
In C-Language there are three logical operators. They are as follows.
Operator meaning Description
&& logical AND True when all conditions are true
|| logical OR True when any one of conditions is true
! logical NOT It gives negation of a condition

B.Sc - V SEM - Computer Science 5


Programming in Java Prepared by S. Nagesh MCA NET

Assignment Operators: Assignment operators are used to assign the result of right side
expression to the left side variable. Assignment operators are +=, -=, *=, /=, %= and =.
Ex: if b= 11, b+=2 means b=b+2  b= 13
If c=11 , c %=3 means c=c%3  c=2
Increment and Decrement Operator: Increment and decrement operators are used to
increase or decrease the value of an operand by one. These are unary operators since there is a
single operand.
Operator meaning Description
++ Increment Increases value of an operand by one
If a=15, a++; then the value of a is 16
-- Decrement Decreases value of an operand by one true
If a=15, a- -; then the value of a is 14
Increment and decrement operators can be used before variable and after variable.
Pre Increment  ++a, if a=10 and b=++a, now a=11 and b=11
Post Increment  a++, if a=10 and b=a++, now a=11 and b=10
Pre Decrement  --a, if a=21 and b= --a, now a=20 and b=20
Post Decrement  a--, if a=21 and b=a--, now a=20 and b=21
Conditional Operator (Ternary operator): The character pair ? and : is called the
Conditional operator or ternary operator. The conditional operator is used to select particular block
depending on the condition.
Syn: variable = (condition) ? value_if_true : value _ if _ false
Ex: if a=10 and b=20
c = (a<b) ? b : a;
If a value is less than b, b is assigned to c or a assigned to c. Now c =20
Bitwise Operators: Bitwise operators are used to perform the operations on binary bits. The
Bitwise Operators are as follows:
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift

8. Conditional Statements (Decision Making Statements)


Conditional statements make the decision by testing a condition. The result of the
test condition may be true or false. There two type of conditional statements in Java. They
are: if – else and switch -case
if – else:
There are different forms of if – else statement.
 Simple if: It is a single selection statement. The general form of simple if statement is as
follows:
Syntax: if (condition)
{
----
}
First test condition is evaluated. If it is true, then statements in if block will be
executed otherwise skipped.
 if – else: It is a double selection statement. The general form of simple if statement is as
follows:

B.Sc - V SEM - Computer Science 6


Programming in Java Prepared by S. Nagesh MCA NET

Syntax: if (condition)
{
Statements if_true;
}
else
{
Statements if_false;
}
First test condition is evaluated. If it is true, then the statements in if block will be
executed and else-block will be skipped. If test condition is false, then the statements in if-
block will be skipped and else-block statements will be executed.
 if – else ladder: It is a multiple selection statement. The general form of simple if
statement is as follows:
Syntax: if (condition1)
{
Statements if_condition1_true;
}
else if (condition2)
{
Statements if_condition2_true;
}
else if (condition3)
{
Statements if_condition3_true;
}
else
{
----
}
First, the condition 1 is evaluated. If it is true, the statements in that if block are
executed and all are skipped. If the condition1 is false, then condition2 is evaluated and
so on. If all conditions are false, then final else statement will be executed.

Switch case:
Switch case is multiple selection statement. The general form of switch case is as
follows:
Syntax: switch (expression)
{
case label1:
statements;
break;

case label2:
statements;
break;
------
default:
statements
}

B.Sc - V SEM - Computer Science 7


Programming in Java Prepared by S. Nagesh MCA NET

First the result of expression is evaluated and matched to case values. If the
match is found that case is executed. If no match case found, then the statements in the
default will be executed. Here break keyword is used to jump the control out of switch
block after execution of particular case.
In switch –case, the result of expression must either character or integer type.

Write a java program to find largest of three numbers


class Largest
{
public static void main(String ar [ ])
{
int a,b,c;
a=10;b=30;c=23;
if(a>b)
{
if(a>c)
{
System.out.println(“Largest no:”+a);
}
else
{
System.out.println(“Largest no:”+c);
}
}
else
{
if(b>c)
{
System.out.println(“Largest no:”+b);
}
else
{
System.out.println(“Largest no:”+c);
}
}
}

9. Loops (Iterative Statements)


Looping statements are used to execute certain statements repeatedly. Java supports
four types of looping statements. They are
 while
 do-while
 for
 for –each

 while loop statement:


The while loop is used to execute a block of statement repeatedly based on a
condition. The condition will be evaluated before entering into loop. It is known as entry
controlled loop.

B.Sc - V SEM - Computer Science 8


Programming in Java Prepared by S. Nagesh MCA NET

Syntax:
while(condition)
{
Statements
Loop counter alteration;
}
Ex:
int i=1;
while (i<=5)
{
System.out.println(“Odd Number:”+i);
i=i+2;
}
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
 do-while loop statement:
The do-while loop is also used to execute a block of statement repeatedly based on a
condition. The condition will be evaluated at the end of the loop. It is known as exit
controlled loop. The statements in the loop will executed at least once.
Syntax: do
{
Statements
Loop counter alteration;
} while(condition);
Ex:
int i=1;
do
{
System.out.println(“Odd Number:”+i);
i=i+2;
}while (i<=5);
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5

 for loop statement:


The for loop execute a block of statements for a specific number of times. It groups
initialization, condition and increment or decrement in a single statement.
Syntax:
for( initialization; condition;increment/decrement)
{
Statements;
}
Ex:
int i;
for(i=1;i<=5;i=i+2)
{
B.Sc - V SEM - Computer Science 9
Programming in Java Prepared by S. Nagesh MCA NET

System.out.println(“Odd Number:”+i);
}
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
 for-each loop statement:
Java 5.0 introduced advanced for loop called as for-each loop. This loop is used to
access each value successively in an array.
Syntax:
for(type var:array)
{
Statements; 10) 453(45
- 450
}
-------
Write a Java program to find reverse of a number 3 –r
class Reverse S=s*10+r =0*10+3=3
{ n=n/10n=45
public static void main(String ar[ ])
10) 45 (4
{
-40
int n=453;
-----
int s=0;
5 -r
System.out.println(“Given number=”+n);
s=s*10+r
while(n!=0) =3*10+5=35
{ n=n/10n=4
int r=n%10;
10) 4 ( 0
s=s*10+r;
-0
n=n/10;
-------
}
4–r
System.out.println(“Reverse number=”+s);
s=s*10+r
}
=35*10+4=354
} // End of the program
n=n/10  n=0;
Compile: javac Reverse.java
here n!=0 condition
Run: java Reverse
false.
Output: Loop terminates.
Given Number=453
Reverse Number=354

Write a program to check whether a given number is prime or not


class Prime
{
public static void main(String ar[ ])
{
int n=19;
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}

B.Sc - V SEM - Computer Science 10


Programming in Java Prepared by S. Nagesh MCA NET

if(c==2)
System.out.println(n+“ is Prime”);
else
System.out.println(n+“ is Not Prime”);
}
} // End of the program

Compile: javac Prime.java


Run: java Prime
Output: 19 is Not Prime
Write a program to find gcd of two numbers.
class gcd
{
public static void main(String ar[ ])
{
int a=16,b=12; b a
int g,r; 12) 16 (1
do -12
{ --------------
r=a%b; 4---r
if(r==0) b a
g=b; 4) 12 (3
else - 12
{ -----------
a=b; 0—r
b=r; Here Remainder=0.
} Hence Devisor is GCD
}whiel(r!=0); Here Devisor is 4.
System.out.println(“Gcd=”+g); GCD=4
}
} // End of the program
Compile: javac gcd.java
Run: java gcd
Output: Gcd =

B.Sc - V SEM - Computer Science 11


Programming in Java Prepared by S. Nagesh MCA NET

CHAPTER-2
DEFINIG CLASSES
10. Class & Object
In object oriented programming, the problem domain is divided into number of
objects. Each object consist data and operations on data. Some objects may share same
properties.
“Collection of objects that have common properties is called as a Class”.
In OOPs a class is defined as a user defined data type that can be used to define
objects as variables. A class definition consist data and operations on data.
Class Declaration: In Java a class can be defined by using a keyword class.
Syntax:
[modifier] class classname [ extends superclass] [ implement interface]
{
Field declarations;
Method definition;
}
Here the keywords inside [ ] brackets are optional. So a basic class definition is as
follows:
class classname
{
Field declarations;
Method definition;
}
Note:
The classname is any valid identifier
Field Declaration: The variables used in a program are declared. Instance variables and
class variables are declared in field declaration part. Variables declared inside class are
called member variables. These variables can be declared as follows:
Syntax:
[modifier] datatype variablename;
Here modifier is any visibility control such as private, public, protected. It is optional.
The default visibility is up to the same package.
Ex:
class Rectangle
{
int length;
int breadth;
}

B.Sc - V SEM - Computer Science 12


Programming in Java Prepared by S. Nagesh MCA NET

Method Definition: A method is block of programming code that performs a specific task.
In Java operations on data is defined as method like functions in c++. In Java methods has
to define inside of the class definition.
Syntax:
[modifier] returntype methodname(parameters list)
{
Statements;
}
Return type is a type of value a method can return. It can be void if no value return. The
method name must be a valid identifier.
Eg: void getdata(int x,int y)
{
length=x;
breadth=y;
}
11. Object Creation
Object is an instance of a class. Object is a variable of a class type. Creation of an
object involves two tasks, declaring and initializing object.
Declaration of Object: Object declarations are same as variable declaration.
Syntax: classname objectname1, objectname2;
Ex: Rectangle r1,r2;
The above declaration would not create an object but it creates a variable.
Initializing an object: After declaring an object a physical copy of an object must be
acquired and assigned to that variable. This can be achieved by new operator. The new
operator creates an object reference by dynamically allocating memory for an object of the
class.
Syntax: objectname = new classname( );
Ex: r1=new Rectangle();
r2=new Rectangle();
Now object r1 & r2 consist its own length and breadth variables.
Declaration and initialization of an object can be done in a single statement as
follows:
Rectangle r1=new Rectangle();
Method Invocation:
Method of a class can’t run on their own. They need to be invoked. Instance methods
will be invoked by the objects of that class.
Syntax:
Objectname.methodname(values);
When an object invokes a method, it can pass certain values to the method and the
method can also return values.
Ex: Rectangle r1=new Rectangle();
r1.getdata(30,20);
B.Sc - V SEM - Computer Science 13
Programming in Java Prepared by S. Nagesh MCA NET

Write a Java Program to calculate area of a rectangular room


class Rectangle
{
int length, breadth;
void getdata(int x,int y)
{
length=x;
breadth=y;
}
void area()
{
int a=length*breadth;
System.out.println(“Area=”+a);
}
}
class Room
{
public static void main(String ar[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.getdata(30,15);
r2.getdata(22,10);
System.out.println(“Area of Room1”);
r1.area();
System.out.println(“Area of Room2”);
r2.area();
}
}
Note: Here there a two classes in a single program. The file name of the program is taken as
Room.java because the main method definition is defined inside of the Room class.
Hence Room class is main class. Hence file name of this program is Room.java
Compile: javac Room.java
R1
Run: java Room Length=30
Output: Breadth=15
Area of Room1
Area= 450
Area of Room2
R2
Area= 220
Length=22
Breadth=10

B.Sc - V SEM - Computer Science 14


Programming in Java Prepared by S. Nagesh MCA NET

12. Method Overloading


The mechanism of defining two or more methods with same name but different
parameters in same class is called as method overloading. Method overloading is used
when objects are required to perform similar operations but using different type of data. In
method overloading the return type may be same or not.
When we call a method with an object, Java matches the method name first, then
number of parameters and then type of parameters to decide which of the method to
execute. Method overloading is an example for static polymorphism.
Eg:
sum(int,int)
sum(int, double)
sum(double, int).
Write a program to demonstrate method Overloading
class overloading
{
void sum(int x, int y)
{
int c=x+y;
System.out.println(“Sum=”+c);
}
void sum(int x, int y,int z)
{
int c=x+y+z;
System.out.println(“Sum=”+c);
}
public static void main(String ar[])
{
Overloading a=new Overloading();
a.sum(10,20);
a.sum(13,50,30);
}
} // End of java Program.

Compile: javac overloading. Java


Run: java overloading
Output:
Sum=30
Sum=93

B.Sc - V SEM - Computer Science 15


Programming in Java Prepared by S. Nagesh MCA NET

13. Constructor
Constructor is a special member method that will be invoked automatically when
object of that class is created. Constructor is used to initialize the instance variables of a
class.
 Constructor name is same as class name.
 The constructors don’t have any return type even void.
 The constructors can’t be private or protected
 Constructors can’t be abstract, final
 Constructors can’t be overridden
 Constructors can be overloaded
In Java there are two types of constructors. They are
1. Default Constructors
2. Parameterized Constructors
Default constructor: A constructor that does not take any parameters is known as default
constructors.
class Abc
{
Abc( )
{
System.out.println(“this is default constructor”);
}
}
Parameterized Constructor: A constructor that takes parameters is called parameterized
constructors. During object creation, the required parameters must be passed to
constructor.
class Abc
{ int x,y;
Abc(int p,int q)
{
x=p;
y=q;
}
}
Here object creation statement must pass arguments to the constructor.
Abc obj=Abc(15,16);
Write a program to demonstrate constructors
class Rectangle
{
int l,b;
Rectangle()
{
l=15,
b=30;
}
Rectangle(int x,int y)
{
l=x;
b=y;
}

B.Sc - V SEM - Computer Science 16


Programming in Java Prepared by S. Nagesh MCA NET

void area()
{
int a=l*b;
System.out.println(“Area=”+a);
}
}
class Room
{
public static void main(String ar[])
{
Rectangle r1=new Rectangle(); // Default constructor
Rectangle r2=new Rectangle(20,50); // Parameterized constructor
r1.area();
r2.area();
}
}

Constructor Overloading:
The mechanism of defining two or more constructors in class definition with
different type of arguments or different number of arguments is called Constructor
Overloading.
class Room
{
int l,b;
Room(int x)
{
l=b=x;
}
Room(int x,int y)
{
l=x;
b=y;
}
}

14. Local Variables, Instance variables, Class Variables (Static Keyword)


The different kinds of variables that Java support are Local variables, instance variables
and Class or Static variables.
Local variables: Local variables are declared inside a method, constructor or a block of
code. Parameters passed to the method are also local variables. The scope of local variables
is limited to the method or block in which they have been defined. They have to be
declared and initialized before they are used. Access specifiers like private, public, and
protected cannot be used with local variables.
Instance Variables: Instance variables are declared inside a class, but outside a method.
They are also called data member or field. An object is allotted memory for all instance
variables. Instance variables are created for every object of that class. They hold different
values for different objects. The scope of the instance variables associated with object of that
class.

B.Sc - V SEM - Computer Science 17


Programming in Java Prepared by S. Nagesh MCA NET

Class / static variables: Class /static variables declaration is preceded with the keyword
static. They are also declared inside a class, but outside a method. There exists only one
copy of static variables per class. All objects of the class share this variable. Static variables
are normally used for constants.
Syntax:
static int var=0;
Static methods: Like static variables, we can also defined methods as static. Such methods
are called static methods. Static methods can be invoked without creation object. Static
methods can be invoked with its class name. Static methods can only access static variables
directly.
Syntax:
static void getdata(parameters);

15. Read User input from Keyboard


In Java, the Scanner class is commonly used to read input from the keyboard. This class
is part of the java.util package and provides methods to read various data types.

The Scanner class provides various methods to read specific data types. commonly used
method in Scanner Class are as follows:
 nextByte(): This method reads byte type of data
 nextShort(): This method reads short type of data
 nextInt(): This method read int type of data
 nextLong(): This method read long type of data
 nextFloat(): This method read float type of data
 nextDouble(): This method read double type of data
 nextLine(): This method reads a line of text.
 nextBoolean(): This method read a Boolean type of data

The following steps are used to read input from the keyboard using the Scanner class.

 Import the Scanner class.


Import the Scanner class from java.util package using import keyword
import java.util.Scanner;
 Create object for Scanner class
An object for Scanner class can be created by passing System.in as a
parameter to the constructor.
Eg: Scanner scan=new Scanner(System.in);
 Call specific method:
Call specific method to read input data. The method returns a value, so that
method calling statement assigned to respective variable.
Eg: To read a string call nextLine() method.
String str=scan.nextLine();
To read an integer value call nextInt() method.
int x=scan.nextInt();

B.Sc - V SEM - Computer Science 18


Programming in Java Prepared by S. Nagesh MCA NET

Example: Write a program to read two numbers find sum.


import java.util.*;
class Scannerdemo
{
public static void main(String ng[])
{
Scanner s=new Scanner(System.in);
int a,b,c;
System.out.println(“Enter two numbers”);
a=s.nextInt();
b=s.nextInt();
c=a+b;
System.out.println(“Sum=”+c);
}
}

B.Sc - V SEM - Computer Science 19


Programming in Java Prepared by S. Nagesh MCA NET

UNIT – II
CHAPTER-3
ARRAYS, STRINGS IN JAVA
1. Defining Arrays & Creating Arrays
An array is a collection of similar type of elements. Arrays are used to store multiple
values in a single variable.
An array is a memory space that can store multiple values of same data type in
continuous memory locations. Individual elements of an array can be accessed using
subscript or index used inside the brackets. The index will starts from 0 (zero) and ends
with size-1. There are two types of arrays.
 One dimensional Array
 Multi dimensional Array
 One Dimensional Arrays
In one – dimensional array single row of values are stored in single variable.
A single subscript or index is required to access individual array elements.
Creation of One-Dimensional Array:
Creating an array is similar object creation and involves following steps.
 Declaring an array
 Creating memory location
Declaring an Array:
A One – dimensional array can be declared as follows:
Syntax:
datatype variable[ ]; OR datatype[ ] variable.
Eg:
int m[];
Creating memory location:
In Java memory location for an array can be created using new operator.
Syntax:
Arrayname = new type[size];
Eg:
m=new int[5];
Array variable declaration and memory creation can be done in a single
statement as given below.
int m[]=new int[10];
Initialization of one dimensional array:
An array variable can be initialized as follows.
Syntax: type array[]={list of values};
int m[ ]={10,15,32,14,2};
 Two Dimensional Array
Two-dimensional array is used to represent a table of values which are
organized in rows and columns. Two indices are used to access individual values
of an array. One index for row, another index for column.
Creating 2-D array:

B.Sc - V SEM - Computer Science 20


Programming in Java Prepared by S. Nagesh MCA NET

A two-dimensional array can be created as same as one-dimensional


array as given below.
Syntax:
datatype array[] [];
array=new type[rowsize][colsize];
Eg:
int m[][];
m = new int[3][3];
The above two statements can be merged into one as below.
int m[][] = new int[3][3];
Initialization of 2-D Array
A two-dimensional array can initialized at the time of their creation as given
below.
Syntax:
Type arra[][]={list of values};
Ex:
int a[ ][ ]={{1,2,3}{4,5,6},{7,8,9}};

Write a program to find sum elements of array.


import java.util.Scanner;
class Sum
{
public static void main(String ng[])
{
int a[]=new int[10];
int n,s=0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter size of array");
n=scan.nextInt();
// Reading array elements
System.out.println("Enter array elements");
for(int i=0;i<n;i++)
{
a[i]=scan.nextInt();
}
// Finding sum of array elements
for(int i=0;i<n;i++)
{
s=s+a[i];
}
System.out.println("Sum of elements of array="+s);
}
}
Compile: javac Sum.java
Run: java Sum
Output: Enter Size of the array
5
Enter array Elements
13 10 15 12 14
Sum of elements of array= 64

B.Sc - V SEM - Computer Science 21


Programming in Java Prepared by S. Nagesh MCA NET

2. Introduction to java.util.Arrays class


The Arrays class in java util package is a utility class that provides static methods to
perform various operations on array variables. The commonly performed operations are
sorting, searching, comparing and converting to strings.
Methods:
 fill(): This method assigns the specified value to each element of specified array.
Arrays.fill(arrayname, value);
 sort(): This method sorts the given array in ascending order.
Arrays.sort(arrayname);
 binarySearch(): This method searches the specified array for the specified value
using binary search algorithm.
int k=Arrays.binarySearch(arrayname, key)
 equals(): Compares two arrays and returns true if the size and values of two arrays
are same.
boolean b=Arrays.equals(arr1,arr2);
 toString(): Returns a string representation of the contents of the specified array
String str=Arrays.toString(arrayname)
3. Strings
String is a collection of characters. In Java strings are implemented with the help of
two classes String and StringBuffer. These classes are defined in java.lang package.
String class:
String class creates a fixed length of strings. In Java strings can be created in two
ways as given below.
String city=”Nalgonda”;
String can be created with the help of string object by passing string literal as an
argument to the constructor.
String city=new String(“Nalgonda”);
String class methods:
The String class provides various methods. The commonly used methods are as follows:
 int length(): It returns number of characters in its calling string.
Ex: String s=new String(“Nalgonda”);
int x=s.length();
Now x value is 8
 int indexOf(char): It returns the index of given characters in its calling String object
Ex: String s=new String(“Nalgonda”);
int x=s.indexOf(‘g’);
Now x value is 3 because index of character g is 3.
 char charAt(int): It returns the characters at a given position in its calling string
object
Ex: String s=new String(“Nalgonda”);
char x=s.charAt(5);
Now x value is ‘n’

B.Sc - V SEM - Computer Science 22


Programming in Java Prepared by S. Nagesh MCA NET

 int compareTo(String): This is used to compare two strings. It returns integer value.
The value is negative if calling string is less than argument string, positive if calling
string is greater than argument string and zero if both are same.
Ex:
String s1=new String(“Nalgonda”);
String s2=new String(“MGU”);
int x=s1.compareTo(s2);
Here s1 is calling String object
s2 is argument string object
Calling string S1 is greater than Argument string s2
hence the value of x is positive value.
 String toUppercase(): It converts all characters in its calling string to upper case and
new string returns.
Ex:
String s1=new String(“Nalgonda”);
String s2=s1.toUppercase();
Now s2=”NALGONDA”;
 String toLowercase(): It converts all characters in its calling string to lower case
letters and return a new string.
Ex:
String s1=new String(“Nalgonda”);
String s2=s1.toLowercase();
Now s2=”nalgonda”;
 String subString(int x, int y): It returns a substring from calling string starts with x
and ends with y.
Ex:
String s1=new String(“Nalgonda”);
String s2=s1.subString(2,5);
Now value of s2 is “lgon”
4. String Buffer Class
StringBuffer is a subclass of String class. StringBuffer class creates a variable length
strings that can be modified. We can insert characters or strings in middle of a sting and
also appended one string at the end of other string.
A StringBuffer object can be created as follows:
StringBuffer city=new StringBuffer(“Nalgonda”); OR
StringBuffer city=”Nalgodnda”;
String Buffer class methods
StringBuffer class definition includes following methods.
 insert(int,string):It inserts a parameter string at the nth position of calling string.
Ex:
StringBuffer s1=new StringBuffer(“Mahtma University”);
s1.insert(6,” Ghandhi ”);
Now the s1 value is Mahatma Gandhi University
B.Sc - V SEM - Computer Science 23
Programming in Java Prepared by S. Nagesh MCA NET

 append(string): It adds a parameter sting at the end of its calling string


Ex:
StringBuffer s1=new StringBuffer(“MGU”);
s1.append(“Nalgonda”);
Now string s1 values is MGUNalgonda
 setCharAt(int, char): It replaces parameter character at the nth position in its calling
string.
StringBuffer s1=new StringBuffer(“NLG”);
s1.setCharAt(0,’M’);
// It replaces the character at 0th position with ‘M’
Now string s1is MLG
 setLength(int): It sets length of calling string.
5. StringTokenizer Class
The StringTokenizer is a java class defined java.util package. StringTokenizer class is
used to break a string into smaller parts, called "tokens," based on a specified set of
delimiter characters. A delimiter is character or set of characters that separate tokens in the
string.
It simplifies the process of splitting a string into its constituent parts, such as words
in a sentence or fields in a data string. You can define the characters that act as separators
between tokens. By default, whitespace characters are used as delimiters. You can also
specify custom delimiters when creating a StringTokenizer object.
Methods:
 StringTokenizer(String str): Creates a tokenizer for the specified string. Uses
default delimiters (whitespace, tabs, etc.).
 StringTokenizer(String str, String delim): Creates a tokenizer for the specified
string using the given delimiters.
 StringTokenizer(String str, String delim, boolean returnDelims): Creates a
tokenizer for the specified string using the given delimiters and specifies whether
the delimiters should be returned as tokens.
 hasMoreTokens(): Returns true if there are more tokens available, false otherwise.
 nextToken(): Returns the next token from the string.
 countTokens(): Returns the number of remaining tokens in the string.
Program to demonstrate StringTokenizer
import java.util.StringTokenizer;
class Splitting
{
public static void main(String ng[])
{
String str="Welcome to Department of Computer Science";
StringTokenizer tokens=new StringTokenizer(str);
while(tokens.hasMoreTokens())
{
System.out.println(tokens.nextToken());
}
}
}

B.Sc - V SEM - Computer Science 24


Programming in Java Prepared by S. Nagesh MCA NET

6. Wrapper Classes
Wrapper classes are used to convert primitive data types into object types. Java API
defines wrapper classes for all its primitive types in java.lang package. The wrapper classes
and their primitive types are as follows:
Byte  byte
Short  short
Integer  int
Long  long
Float  float
Double  double
Character  char
Boolean  boolean
These wrapper classes define constructors and other methods to convert primitive data
values into objects and objects into their primitive types.
 Primitive numbers can be converted into object number using respective constructor
method.
Ex:
int x=10;
Integer obj=new Integer(x);
Now 10 is an object.

 Object format numbers can be converted into primitive number using typeValue()
method. Here type is based data type.
int x=obj.intValue();
float y=obj.floatValue();
 Numeric String objects can be converted into primitive numbers by using parser
method.
parseInt() defined in Integer class
parseLong() defined in Long class
Ex:
String s1=”245”;
Now the number 245 is in string format. This string format can be converted into
integer type using parseInt() method of Integer class.
int x=Integer.parseInt(s1);
Now the number 245 is an integer.

B.Sc - V SEM - Computer Science 25


Programming in Java Prepared by S. Nagesh MCA NET

UNIT-II
Chapter – 4
INHERITANCE, INTERFACES AND PACKAGES IN JAVA

7. Inheritance
The process of acquiring object properties of another object is known as inheritance.
Defining a new class from already existing class is known as inheritance. The new class is
known as sub class or derived or child class. The existing class is known as super class, base
class or parent class. The sub class gets all properties and methods of its super class and can
have additional variables and methods. The mechanism of inheritance enables reusability
of existing code.
Defining sub class:
In Java, classes are inherited from another class by using extends keyword.
Syntax;
class subclassname extends superclassname
{
Field declaration;
Method definition;
}
Ex:
class Base
{
int x;
}
class Derived extends Base
{
int y;
}

 Types of inheritance
There are 5 types of inheritances. They are as follows:
 Single inheritance
 Multilevel inheritance
 Multiple inheritance
 Hierarchical inheritance
 Hybrid Inheritance
Single Inheritance:
Deriving one class from a single Base class is known as Single inheritance.

A Base Class
class A
{
int x;
}
class B extends A B Derived class
{
int y;
}
B.Sc - V SEM - Computer Science 26
Programming in Java Prepared by S. Nagesh MCA NET

Multilevel Inheritance:
Defining a class from already derived class is known as multilevel inheritance.

A Base Class

Base Class B Derived class

C Derived class

class A
{
int x;
}
class B extends A
{
int y;
}
class C extends B
{
int z;
}
Multiple Inheritance
Deriving a single class from more than one base class is known multiple inheritance.
Java does not support multiple inheritance because the keyword extends can inherit
properties of only one class. But multiple inheritance can achieved with concept of
interface.

Base Class A B Base Class

C Derived class
Hierarchical inheritance
Deriving multiple classes from single base class is called hierarchical inheritance.

A Base Class

Derived Class B C Derived class

B.Sc - V SEM - Computer Science 27


Programming in Java Prepared by S. Nagesh MCA NET

class A
{
int x;
}
class B extends A
{
int y;
}
class C extends A
{
int z;
}
Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.

C D

Write a program to demonstrate Single Inheritance


class Rectangle
{
int length, breadth;
void getdata(int x,int y)
{
length=x;
breadth=y;
}
void area()
{
int a=length&breadth;
System.out.println(“Area=”+a);
}
}
class Rect extends Rectangle
{
int height;
void readdata(int h)
{
height=h;
}
void volume()
{
int v=length*breadth*height;
System.out.println(“Volume=”+v);
}
}
B.Sc - V SEM - Computer Science 28
Programming in Java Prepared by S. Nagesh MCA NET

class Single
{
public static void main(String ar[])
{
Rect r=new Rect();
r.getdata(30,15);
r.readdata(16);
r.area();
r.volume();

}
}
8. Method Overriding
The mechanism of defining a method in sub class with the same name and same
signature as in super class method is known as method overriding. The subclass method
override super class method that means the super class method is hidden.
class A
{
void show()
{
System.out.println(“Super class”);
}
}
class B extends A
{
void show()
{
System.out.println(“Sub class”);
}
}
class override
{
public static void main(String ar[])
{
B obj=new B();
B.show();
}
}

Compile: javac override.java


Run: java override
Output: Sub Class

9. Final Keyword
The keyword final is used for the following purposes
 To declare a symbolic constants. The final keyword is used to define a variable that
does not change
final int a=10;

B.Sc - V SEM - Computer Science 29


Programming in Java Prepared by S. Nagesh MCA NET

 The final keyword is used to define a method that prevents not overriding in
subclass.
final void display()
{
statements
}
 The final keyword is used with class declaration to disallow a class to be inherit.
final class Abc
{
Body of the class
}
10. Abstract Class
A method declaration without definition is known as abstract method. Abstract
methods are defined using a keyword abstract.
abstract void display(); // It is abstract method

A class definition with one or more abstract methods along with normal methods is
known as abstract class.
Abstract classes must be inherited to provide definition for their abstract methods by
overriding them. If its subclass doesn’t implement all the abstract methods then that sub
class also becomes abstract class.
The abstract class can’t be instantiated but can have reference variables. Abstract
class can have constructors, variables and non-abstract methods.
abstract class Abc
{
int x;
void getdata(int p);
{
x=p;
}
abstract void display();
}
class Xyz extends Abc
{
void display()
{
System.out.println(“X=”+x);
}
}

11. Interface
An interface is like a class with all abstract methods and final variables. An interface
doesn’t specify any code to implement. Therefore it is responsibility of the class that
implements an interface to define the code for these abstract methods.

The concept of interface was introduced to implement multiple inheritance. In Java a


class can extend one class and can implement many interfaces at the same time to achieve
concept of multiple inheritance.
B.Sc - V SEM - Computer Science 30
Programming in Java Prepared by S. Nagesh MCA NET

Defining an interface:
The keyword interface is used to define an interface.
Syntax:
interface interface_name
{
Variable declaration;
Method declaration;
}
Eg:
interface Abc
{
int a=10;
void display();
}
Implementing interface:
Interfaces are inherited to classes to provide the implementation code for abstract
methods. The keyword implements is used to implement an interface.
Syntax:
class class_name implements interface_name
{
Body of class
}
A class can implement more than one interface and an interface can be implemented
by more than one class.
The implementing class must provide the definition for all the methods of interface
otherwise that class becomes abstract.
class Xyz implements Abc
{
void display()
{
System.out.println(a);
}
}

12. Package
Package is a group of classes, interfaces and sub packages. The grouping is usually
done according to functionality. Package is a container for classes.
Packages provide a way to hide classes, thus preventing other program to access.
The concept of package increases the reusability of existing code. Java packages are
classified into two types.
 Java API packages (System defined, predefined)
 User Defined Packages
Java API Packages: Java Application Programming Interface (API) provides a large
number of classes grouped into different packages according to their functionality. The
frequently used API packages are as follows:
 java.lang: It includes language support classes. These classes are automatically
imported.
 java.io: It includes input / output supporting classes.
B.Sc - V SEM - Computer Science 31
Programming in Java Prepared by S. Nagesh MCA NET

 java.until: In includes language utility classes such as date, time etc;


 java.applet: It includes classes for implementing applets.
 java.awt: It includes classes for implementing graphical user interfaces
 java.net: It includes classes for networking classes.
 java.sql: It includes classes for implementing JDBC connections.
User Defined Packages
The programmers may define their own class libraries using packages. Such packages
are called as user defined packages.
Creating a User Defined Packages:
Creating user defined packages involves following steps.
1. Declare the package at the beginning of program using package keyword
Syntax: package package_name;
Ex: package Mypack;
2. Define classes under the package and declare one of them as a public.
3. Create a subfolder with the name of package name under the folder where the
main source files are stored.
4. Save the program with name of public class name in sub folder.
5. Compile the program. The byte code files are created in sub folder.
Ex: package mypack;
public class Abc
{
public int sum(int x,int y)
{ return(x+y);
}
}
Accessing and using packages
The members of a package can be accessed in other packages or programs by using
fully qualified name or by using import statement.
Fully qualified name: This is done by using package name and class name
package_name.class_name
mypack.Abc;
import statement: The import statement is used to include classes of one package in
another package. This most of first line of the program but after package declaration.
Syntax:
import package_name.class_Name;
Ex:
import mypack.Abc;
We can import all classes of a package using wild card characters *;
import mypack.*;
The above statement imports all the public classes of mypack package.

B.Sc - V SEM - Computer Science 32


Programming in Java Prepared by S. Nagesh MCA NET

Eg:
import pack.Abc;
class Demopack
{
public static void main(String ar[])
{
int a=10,b=20;
Abc obj=new Abc();
int c=obj.sum(a,b);
System.out.println(“sum=”+c);
}
}
13. Access Specifiers
Access Specifiers defines, how much an element (class, method, variable) is exposed
to other classes and packages. There are four types of access specifiers in Java. They are
Public, Private, Protected and Default
The following table shows the access protection of element.
Same Sub Class Non-Sub class Sub Class Non-Sub Class &
Class Same Package Same Package Other Package Other Package
public Yes Yes Yes Yes Yes
private Yes No No No No
protected Yes Yes No Yes No
default Yes Yes Yes No No
14. Inner Classes
In Java, an inner class is a class defined within another class or interface. It groups
logically related classes, enhancing encapsulation and making code more readable and
aligned with real-world object-oriented design.
Types of Inner Classes:There are basically four types of inner classes in java.
a. Nested Inner Class
b. Method Local Inner Classes
c. Static Nested Classes
d. Anonymous Inner Classes
a. Nested Inner Class: It can access any private instance variable of the outer class. Like
any other instance variable, we can have access modifier private, protected, public and
default modifier.
Eg: class Outer {
class Inner {
public void show()
{
System.out.println("In a nested class method");
}
}
}

B.Sc - V SEM - Computer Science 33


Programming in Java Prepared by S. Nagesh MCA NET

b. Method Local Inner Class: Inner class can be declared within a method of an outer
class
class Outer {
void outerMethod()
{
System.out.println("inside outerMethod");
class Inner {
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
}
}
c. Static Inner Class: A static class defined inside another class. It cannot access non-static
members of the outer class directly.
class Outer
{
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
static class Inner {
public static void display()
{
System.out.println("inside inner class Method");
}
}
}
d. Anonymous Inner Class: An anonymous class in Java is an inner class which is declared
without any class name at all. In other words, a nameless inner class in Java is called an
anonymous inner class. Since it does not have a name, it cannot have a constructor.
Anonymous inner classes are used when you want to create a simple class that is needed
for one time only for a specific purpose.
Eg:
Test t=new Test()
{
public void inner_method()
{
System.out.println(“This is anonymous class”);
}
};

B.Sc - V SEM - Computer Science 34

You might also like