100% found this document useful (2 votes)
7K views42 pages

Guru Internship Report

The document is an internship report submitted by Guru Kiran to fulfill the requirements for a Bachelor of Engineering degree in Computer Science and Engineering. It discusses an internship focused on learning about the Java programming language and its applications. It provides an overview of key Java concepts like classes, objects, OOPs principles, exceptions handling, collections framework and file handling. The report aims to help readers understand why Java is studied and what can be achieved with the language.

Uploaded by

Prathik Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
7K views42 pages

Guru Internship Report

The document is an internship report submitted by Guru Kiran to fulfill the requirements for a Bachelor of Engineering degree in Computer Science and Engineering. It discusses an internship focused on learning about the Java programming language and its applications. It provides an overview of key Java concepts like classes, objects, OOPs principles, exceptions handling, collections framework and file handling. The report aims to help readers understand why Java is studied and what can be achieved with the language.

Uploaded by

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

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

Jnana Sangama, Belgaum-590014

AN INTERNSHIP REPORT
ON
“JAVA AND APPLICATIONS”
Submitted in the partial fulfilment for the requirement of 8th Semester

BACHELOR OF ENGINEERING
IN
COMPUTER SCIENCE & ENGINEERING
Submitted By

GURU KIRAN (1BC16CS002)

Under the Guidance of


Mrs. KAVITHA.T.M
HOD. Dept. of CSE,
BCET

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


BANGALORE COLLEGE OF ENGINEERING & TECHNOLOGY
Bangalore-560099

Dept of CSE
Acknowledgement

I would like to profoundly thank Management of Bangalore College of Engineering and


Technology for providing such a healthy environment for the successful completion of project work.

I would like to express my thanks to the Principal Dr.CHANNANKAIAH, PhD for their
encouragement that motivated me for the successful completion of my internship.

It gives me immense pleasure to thank Mrs. KAVITHA.T.M. Professor and Head of Department for
her constant support and encouragement and for giving me such a wonderful opportunity to expand my
knowledge for my own branch and giving me guidelines to present my knowledge which i gained during the
course. It helped me a lot to realize of what we study for.

I would like to thank my friends who helped me to make my work more organized and well-stacked
till the end.

Next, I would thank Microsoft for developing such a wonderful tool like MS Word. It helped my
work a lot to remain error-free.

Last but clearly not the least, I would thank The Almighty for giving me strength to
complete my report on time.

-Guru kiran (1BC16CS002)

Dept of CSE
Dept of CSE
1.

Dept of CSE
ABSTRACT

This report is based on the knowledge and skills i aquired during the course .The report objective is
to deliver the concept of the subjects learned.

This report is an attempt to provide the advantages of the programming language java and its uses
along with the knowledge of Sequential programming language to readers. It helps students understand why
we need to study java and what we can achieve through this subject. This Language can be implemented on
multiple platforms irrespective of the platform . It’s a full-featured object oriented language and has vast
usage around the world. Java is a Robust language. The basic point of this report is make the readers
understand the Sequential and object orented language”JAVA”.
The report analyses the system requirements and then comes up with the requirements specifications
needed as a sql or java developer. It studies other related systems and then come up with system
specifications. The system is then designed in accordance with specifications to satisfy the requirements.
The system design is then implemented with any IDE such as ECLLIPSE . The system is designed as an
interactive and content management system. Creating and managing requirements is a challenge of IT,
systems and product development projects or indeed for any activity where you have to manage a
contractual relationship.

Dept of CSE
Table of Contents
1. Introduction
 JAVA Programming Language.
 JAVA Fundamentals and Features.
2. Classes and Objects.
3. JAVA OOPS Concepts.
4. Interfaces in JAVA.
5. Exception Handling in JAVA.
6. Collection Framework in JAVA.
7. File Handling in JAVA.

Dept of CSE
INTRODUCTION
Software:
 It is an automated version of manual work.
 Software can also be considered as a automated
Solution fro a real world problem.
 Typically a software may contain UI components
,programs,Storage components……etc.
 A program is nothing but set of instructions for a
hardware of a platform.
 A platform is a combination of process and Operating system .

EgàWindows Android.

JAVA
What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of


Oracle) in the year 1995. James Gosling is known as the father of Java. Before
Java, its name was Oak. Since Oak was already a registered company, so James
Gosling and his team changed the Oak name to Java.

Platform: Any hardware or software environment in which a program runs, is


known as a platform. Since Java has a runtime environment (JRE) and API, it is
called a platform.

Dept of CSE
Java Example
Let's have a quick look at Java programming example. A detailed description of
Hello Java example is available in next page.

class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}
Application
According to Sun, 3 billion devices run Java. There are many devices where Java
is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every
machine. Examples of standalone application are Media player, antivirus, etc.
AWT and Swing are used in Java for creating standalone applications.

2) Web Application
Dept of CSE
An application that runs on the server side and creates a dynamic page is called a
web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is
called enterprise application. It has advantages of the high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.

Java Platforms / Editions


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


It is a Java programming platform. It includes Java programming APIs such as
java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core
topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)


It is an enterprise platform which is mainly used to develop web and enterprise
applications. It is built on the top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)


It is a micro platform which is mainly used to develop mobile applications.

Dept of CSE
4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user
interface API

Dept of CSE
FEATURES OF JAVA
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are
also some excellent features which play an important role in the popularity of this
language. The features of Java are also known as java buzzwords.

A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
Dept of CSE
8. Interpreted
9. High Performance

10.Multithreaded

11.Distributed

12.Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C+
+).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

Object-oriented
Java is an Object oreinted programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Dept of CSE
Platform Independent

Java is platform independent because it is different from other languages


like C, C++, etc. which are compiled into platform specific machines while Java
is a write once, run anywhere language. A platform is the hardware or software
environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java


provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms.
It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere(WORA).

Dept of CSE
Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime


Environment(JRE) which is used to load Java classes into the Java Virtual
Machine dynamically. It adds security by separating the package for the
classes of the local file system from those that are imported from network
sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can
violate access right to objects.

Dept of CSE
o Security Manager: It determines what resources a class can access such
as reading and writing to the local disk.

Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptography, etc.

Robust
Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java
Virtual Machine to get rid of objects which are not being used by a Java
application anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit


architecture and 4 bytes of memory for 64-bit architecture. However, it occupies
4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.

Dept of CSE
High-performance
Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code. It is still a little bit slower than a
compiled language (e.g., C++). Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of
Java makes us able to access files by calling the methods from any machine on
the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.

Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage


collection).

Dept of CSE
OBJECTS AND CLASSES IN JAVA
What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.

Dept of CSE
For Example, Pen is an object. Its name is Reynolds; color is white, known as its
state. It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Dept of CSE
What is a class in Java
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Dept of CSE
Syntax to declare a class:
1. class <class_name>{  
2.     field;  
3.     method;  
4. }  

Instance variable in Java


A variable which is created inside the class but outside the method is known as
an instance variable. Instance variable doesn't get memory at compile time. It
gets memory at runtime when an object or instance is created. That is why it is
known as an instance variable.

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory
in Heap memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id
and name. We are creating the object of the Student class by new keyword and
printing the object's value.

Here, we are creating a main() method inside the class.

1. //Java Program to illustrate how to define a class and fields  
2. //Defining a Student class.  
3. class Student{  
4.  //defining fields  
5.  int id;//field or data member or instance variable  
6.  String name;  
7.  //creating main method inside the Student class  
8.  public static void main(String args[]){  
9.   //Creating an object or instance  
10.   Student s1=new Student();//creating an object of Student  
Dept of CSE
11.   //Printing values of the object  
12.   System.out.println(s1.id);//accessing member through reference variable  
13.   System.out.println(s1.name);  
14.  }  
15. }  
3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference


Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference variable.

1. class Student{  
2.  int id;  
3.  String name;  
4. }  
5. class TestStudent2{  
6.  public static void main(String args[]){  
7.   Student s1=new Student();  
8.   s1.id=101;  
9.   s1.name="Sonoo";  
10.   System.out.println(s1.id+" "+s1.name);//printing members with a whit
e space  
11.  }  
12. } 
We can also create multiple objects and store information in it through
reference variable.

Dept of CSE
1. class Student{  
2.  int id;  
3.  String name;  
4. }  
5. class TestStudent3{  
6.  public static void main(String args[]){  
7.   //Creating objects  
8.   Student s1=new Student();  
9.   Student s2=new Student();  
10.   //Initializing objects  
11.   s1.id=101;  
12.   s1.name="Sonoo";  
13.   s2.id=102;  
14.   s2.name="Amit";  
15.   //Printing data  
16.   System.out.println(s1.id+" "+s1.name);  
17.   System.out.println(s2.id+" "+s2.name);  
18.  }  
19. }  

Method in Java

In Java, a method is like a function which is used to expose the behavior of an


object.

Advantage of Method
o Code Reusability
o Code Optimization

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method.
Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
Dept of CSE
1. class Student{  
2.  int rollno;  
3.  String name;  
4.  void insertRecord(int r, String n){  
5.   rollno=r;  
6.   name=n;  
7.  }  
8.  void displayInformation(){System.out.println(rollno+" "+name);}  
9. }  
10. class TestStudent4{  
11.  public static void main(String args[]){  
12.   Student s1=new Student();  
13.   Student s2=new Student();  
14.   s1.insertRecord(111,"Karan");  
15.   s2.insertRecord(222,"Aryan");  
16.   s1.displayInformation();  
17.   s2.displayInformation();  
18.  }  
19. }  

As you can see in the above figure, object gets the memory in heap memory area. The reference
variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.

Dept of CSE
3) Object and Class Example: Initialization through a
constructor
Object and Class Example: Employee
1. class Employee{  
2.     int id;  
3.     String name;  
4.     float salary;  
5.     void insert(int i, String n, float s) {  
6.         id=i;  
7.         name=n;  
8.         salary=s;  
9.     }  
10.     void display(){System.out.println(id+" "+name+" "+salary);}  
11. }  
12. public class TestEmployee {  
13. public static void main(String[] args) {  
14.     Employee e1=new Employee();  
15.     Employee e2=new Employee();  
16.     Employee e3=new Employee();  
17.     e1.insert(101,"ajeet",45000);  
18.     e2.insert(102,"irfan",25000);  
19.     e3.insert(103,"nakul",55000);  
20.     e1.display();  
21.     e2.display();  
22.     e3.display();  
23. }  
24. } 

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

1. class Rectangle{  
2.  int length;  
3.  int width;  
4.  void insert(int l, int w){  
Dept of CSE
5.   length=l;  
6.   width=w;  
7.  }  
8.  void calculateArea(){System.out.println(length*width);}  
9. }  
10. class TestRectangle1{  
11.  public static void main(String args[]){  
12.   Rectangle r1=new Rectangle();  
13.   Rectangle r2=new Rectangle();  
14.   r1.insert(11,5);  
15.   r2.insert(3,15);  
16.   r1.calculateArea();  
17.   r2.calculateArea();  
18. }  
19. }  

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.

Dept of CSE
Anonymous object

Anonymous simply means nameless. An object which has no reference is known


as an anonymous object. It can be used at the time of object creation only.

If you have to use an object only once, an anonymous object is a good approach.
For example:

1. new Calculation();//anonymous object  

Calling method through a reference:

1. Calculation c=new Calculation();  
2. c.fact(5);  

Calling method through an anonymous object

1. new Calculation().fact(5);  
Dept of CSE
Let's see the full example of an anonymous object in Java.

1. class Calculation{  
2.  void fact(int  n){  
3.   int fact=1;  
4.   for(int i=1;i<=n;i++){  
5.    fact=fact*i;  
6.   }  
7.  System.out.println("factorial is "+fact);  
8. }  
9. public static void main(String args[]){  
10.  new Calculation().fact(5);//calling method with anonymous object  
11. }  
12. }  

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

1. int a=10, b=20;  

Initialization of refernce variables:

1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects  

Let's see the example:

1. //Java Program to illustrate the use of Rectangle class which  
2. //has length and width data members  
3. class Rectangle{  
4.  int length;  
5.  int width;  
6.  void insert(int l,int w){  
7.   length=l;  
8.   width=w;  
9.  }  
10.  void calculateArea(){System.out.println(length*width);}  
Dept of CSE
11. }  
12. class TestRectangle2{  
13.  public static void main(String args[]){  
14.   Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
15.   r1.insert(11,5);  
16.   r2.insert(3,15);  
17.   r1.calculateArea();  
18.   r2.calculateArea();  
19. }  
20. }  
Real World Example: Account

1. //Java Program to demonstrate the working of a banking-system  
2. //where we deposit and withdraw amount from our account.  
3. //Creating an Account class which has deposit() and withdraw() methods  
4. class Account{  
5. int acc_no;  
6. String name;  
7. float amount;  
8. //Method to initialize object  
9. void insert(int a,String n,float amt){  
10. acc_no=a;  
11. name=n;  
12. amount=amt;  
13. }  
14. //deposit method  
15. void deposit(float amt){  
16. amount=amount+amt;  
17. System.out.println(amt+" deposited");  
18. }  
19. //withdraw method  
20. void withdraw(float amt){  
21. if(amount<amt){  
22. System.out.println("Insufficient Balance");  
23. }else{  
24. amount=amount-amt;  
Dept of CSE
25. System.out.println(amt+" withdrawn");  
26. }  
27. }  
28. //method to check the balance of the account  
29. void checkBalance(){System.out.println("Balance is: "+amount);}  
30. //method to display the values of an object  
31. void display(){System.out.println(acc_no+" "+name+" "+amount);}  
32. }  
33. //Creating a test class to deposit and withdraw amount  
34. class TestAccount{  
35. public static void main(String[] args){  
36. Account a1=new Account();  
37. a1.insert(832345,"Ankit",1000);  
38. a1.display();  
39. a1.checkBalance();  
40. a1.deposit(40000);  
41. a1.checkBalance();  
42. a1.withdraw(15000);  
43. a1.checkBalance();  
44. }}   

Dept of CSE
JAVA OOPS CONCEPTS
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is
a paradigm that provides many concepts, such as inheritance, data
binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The


programming paradigm where everything is represented as an object is known as a
truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for


example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.

Dept of CSE
 

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Dept of CSE
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example:
to convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association
between the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Dept of CSE
Let's understand the relationship with real-time examples. For example, One country
can have one prime minister (one to one), and a prime minister can have many
ministers (one to many). Also, many MP's can have one prime minister (many to one),
and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation

Aggregation is a way to achieve Association. Aggregation represents the


relationship where one object contains other objects as a part of its state. It
represents the weak relationship between objects. It is also termed as a has-
a relationship in Java. Like, inheritance represents the is-a relationship. It is
another way to reuse objects.

Composition

The composition is also a way to achieve Association. The composition


represents the relationship where one object contains other objects as a part of its
state. There is a strong relationship between the containing object and the
dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will be
deleted automatically.

Advantage of OOPs over Procedure-oriented programming language


1) OOPs makes development and maintenance easier, whereas, in a procedure-
oriented programming language, it is not easy to manage if code grows as project
size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming


language, global data can be accessed from anywhere.

Dept of CSE
Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively.
We can provide the solution of real word problem if we are using the Object-
Oriented Programming language.

What is the difference between an object-oriented programming


language and object-based programming language?
Object-based programming language follows all the features of OOPs except
Inheritance. JavaScript and VBScript are examples of object-based programming
languages.

Dept of CSE
INTERFACES IN JAVA
Like a class, an interface can have methods and variables, but the methods declared in
an interface are by default abstract (only method signature, no body).  
 Interfaces specify what a class must do and not how. It is the blueprint of the
class.
 An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies
a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
 A Java library example is, Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Syntax :

interface <interface_name> {

// declare constant fields

// declare methods that abstract

// by default.
}
To declare an interface, use interface keyword. It is used to provide total abstraction.
That means all the methods in an interface are declared with an empty body and are
public and all fields are public, static and final by default. A class that implement
interface must implement all the methods declared in the interface. To implement
interface use implements keyword.

Why do we use interface ?


 It is used to achieve total abstraction.
 Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance .
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?

Dept of CSE
The reason is, abstract classes may contain non-final variables, whereas variables
in interface are final, public and static.

// A simple interface
interface Player
{
    final int id = 10;
    int move();
}
To implement an interface we use keyword: implement

// Java program to demonstrate working of 


// interface.
import java.io.*;
  
// A simple interface
interface In1
{
    // public, static and final
    final int a = 10;
  
    // public and abstract 
    void display();
}
  
// A class that implements the interface.
class TestClass implements In1

Dept of CSE
{
    // Implementing the capabilities of
    // interface.
    public void display()
    {
        System.out.println("Geek");
    }
  
    // Driver Code
    public static void main (String[] args)
    {
        TestClass t = new TestClass();
        t.display();
        System.out.println(a);
    }
}

Dept of CSE
EXCEPTION HANDLING IN JAVA

The Exception Handling in Java is one of the powerful mechanism to handle


the runtime errors so that normal flow of the application can be maintained.

In this page, we will learn about Java exceptions, its type and the difference
between checked and unchecked exceptions.

What is Exception in Java


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is
why we use exception handling. Let's take a scenario:

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5;//exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;  
9. statement 9; 

Dept of CSE
COLLECTIONS IN JAVA
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.
What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Dept of CSE
FILE HANDLING IN JAVA

Java FileWriter and FileReader classes are used to write and read data from text files
(they are Character Stream classes). It is recommended not to use the FileInputStream
and FileOutputStream classes if you have to read and write any textual information as
these are Byte stream classes.
FileWriter
FileWriter is useful to create a file writing characters into it.

 This class inherits from the OutputStream class.


 The constructors of this class assume that the default character encoding and the
default byte-buffer size are acceptable. To specify these values yourself, construct
an OutputStreamWriter on a FileOutputStream.
 FileWriter is meant for writing streams of characters. For writing streams of raw
bytes, consider using a FileOutputStream.
 FileWriter creates the output file , if it is not present already.
Constructors:
 FileWriter(File file) – Constructs a FileWriter object given a File object.
 FileWriter (File file, boolean append) – constructs a FileWriter object given a
File object.
 FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with
a file descriptor.
 FileWriter (String fileName) – constructs a FileWriter object given a file name.
 FileWriter (String fileName, Boolean append) – Constructs a FileWriter
object given a file name with a Boolean indicating whether or not to append the
data written.
Methods:
 public void write (int c) throws IOException – Writes a single character.
 public void write (char [] stir) throws IOException – Writes an array of
characters.
 public void write(String str)throws IOException – Writes a string.
 public void write(String str,int off,int len)throws IOException – Writes a
portion of a string. Here off is offset from which to start writing characters and len
is number of character to write.
 public void flush() throws IOException flushes the stream
Dept of CSE
 public void close() throws IOException flushes the stream first and then closes
the writer.
Reading and writing take place character by character, which increases the number of
I/O operations and effects performance of the system.BufferedWriter can be used
along with FileWriter to improve speed of execution.

Following program depicts how to create a text file using FileWriter


// Creating a text File using FileWriter

import java.io.FileWriter;

import java.io.IOException;

class CreateFile

public static void main(String[] args) throws IOException

// Accept a string

String str = "File Handling in Java using "+

" FileWriter and FileReader";

// attach a file to FileWriter

FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write

// into FileWriter

for (int i = 0; i < str.length(); i++)

fw.write(str.charAt(i));

System.out.println("Writing successful");

//close the file


Dept of CSE
fw.close();

}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
 This class inherit from the InputStreamReader Class.
 The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself,
construct an InputStreamReader on a FileInputStream.
 FileReader is meant for reading streams of characters. For reading streams of
raw bytes, consider using a FileInputStream.
Constructors:
 FileReader(File file) – Creates a FileReader , given the File to read from
 FileReader(FileDescripter fd) – Creates a new FileReader , given the
FileDescripter to read from
 FileReader(String fileName) – Creates a new FileReader , given the name of
the file to read from
Methods:
 public int read () throws IOException – Reads a single character. This method
will block until a character is available, an I/O error occurs, or the end of the
stream is reached.
 public int read(char[] cbuff) throws IOException – Reads characters into an
array. This method will block until some input is available, an I/O error occurs, or
the end of the stream is reached.
 public abstract int read(char[] buff, int off, int len) throws IOException –
Reads characters into a portion of an array. This method will block until some
input is available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
 public void close() throws IOException closes the reader.
 public long skip(long n) throws IOException –Skips characters. This method
will block until some characters are available, an I/O error occurs, or the end of
the stream is reached.
Parameters:
n – The number of characters to skip

Dept of CSE

You might also like