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

Report Java Programming Languages

This document is a report submitted by Subhash Kumar for the partial fulfillment of a bachelor's degree in computer science and engineering. It discusses Java programming for software development. The abstract indicates that the report will cover writing applications in Java using Swing and some of the large libraries and advanced aspects involved. It then acknowledges and thanks those who helped enable the completion of the report, including faculty members and peers.

Uploaded by

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

Report Java Programming Languages

This document is a report submitted by Subhash Kumar for the partial fulfillment of a bachelor's degree in computer science and engineering. It discusses Java programming for software development. The abstract indicates that the report will cover writing applications in Java using Swing and some of the large libraries and advanced aspects involved. It then acknowledges and thanks those who helped enable the completion of the report, including faculty members and peers.

Uploaded by

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

1


Report 
on 
JAVA PROGRAMMING FOR SOFTWARE DEVELOPMENT
Submitted in Partial Fulfilment of the Requirement for 
 the Award of the Degree of 

BACHELOR OF TECHNOLOGY 
IN 

COMPUTER SCIENCE & ENGINEERING 


BY 

Subhash Kumar
(18BTCSE009) 

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY

VAUGH INSTITUTE OF AGRICULTURAL ENGINEERING AND T
ECHNOLOGY
 FACULTY OF ENGINEERING AND TECHNOLOGY 
SAM HIGINBOTTOM UNIVERSITY OF AGRICULTURE,
TECHNOLOGY AND SCIENCES 
(FORMELY ALLAHABAD AGRICULTURAL INSTITUTE) 
NAINI, PRAYAGRAJ-211007 
2020
2

DECLARATION

I, Subhash Kumar (15BTCSE032), declare that the work presented in


this report titled ‘ JAVA Programming for software Development ’
submitted to the Department of Computer Science & Information
Technology, in the Faculty of Engineering & Technology, Sam
Higginbottom University of Agriculture, Technology & Sciences, Naini,
Prayagraj, for the award of the Bachelor of Technology degree in
Computer Science and Engineering is an original work. I have neither
plagiarized nor submitted the same work for the award of any other
degree. In case this undertaking is found incorrect, my degree may be
withdrawn unconditionally by the University.

Date: Signature of Student


Place: Prayagraj Subhash Kumar
(P.ID.15BTCSE032)
3

ABSTRACT

Writing applications in Java using Swing can be quite a daunting experience which requires
understanding of some large libraries, and fairly advanced aspects of Java. In a graphical
system, a windowing toolkit is usually responsible for providing a framework to make it
relatively painless for a graphical user interface (GUI) to render the right bits to the screen
at the right time.
4

ACKNOWLEGEMENT

I would like to express my deepest appreciation to all those who provided me


the possibility to complete this report.  A special gratitude I give to our final
year project manager, [Mr Mohit Paul], whose contribution in stimulating
suggestions and encouragement, helped me to coordinate my project especially
in writing this report.

Furthermore, I would also like to acknowledge with much appreciation the


crucial role of the staff, who gave the permission to use all required equipment
and the necessary materials to complete the task “JAVA FOR SOFTWARE
DEVELOPMENT”.  A special thanks goes to my mate, who help me to assemble
the parts and gave suggestion about the task.  Last but not least, many thanks
go to the head of the project, [Mr.William Jeberson] whose have invested his
full effort in guiding the team in achieving the goal. I have to appreciate the
guidance given by other supervisor as well as the panels especially in our
project presentation that has improved our presentation skills thanks to their
comment and advices.
5

Table of content
TITLE PAGE NO.

DECLARATION

ABSTRACT i

ACKNOWLEDGEMENT ii

TABLE OF CONTENT iii

LIST OF TABLES iv

LIST OF FIGURES v

LIST OF NOTATION/SYMBOLS vi

LIST OF ABBREVIATIONS vii

CHAPTER 1 INTRODUCTION

1.1 Introduction 1

1.2 Basic 3

CHAPTER 2 OOP CONCEPT-1

2.1 Classes and object 4

2.2 Constructors 5

2.3 Inheritance 6

CHAPTER 3 OOP CONCEPT-2


6

3.1 Composition 7

3.2 Encapsulation 8

3.3 Polymorphism 9

CHAPTER 4 JAVA GENERICS

4.1 Generics Introduction 10

4.2 Our generic class 11

4.3 Generics challenges 12

CHAPTER 5 SUMMARY & CONCULION

5.1 Future scope

5.2 Summary

5.3 Conclusion

APPENDIX

A.Certificate
7

CHAPTER 1 INTRODUCTION

1.1 Introduction

Java is a programming language created by James Gosling from


Sun Microsystems (Sun) in 1991. The target of Java is to write a
program once and then run this program on multiple operating
systems. The first publicly available version of Java (Java 1.0) was
released in 1995. Sun Microsystems was acquired by the Oracle
Corporation in 2010. Oracle has now the steer Manship for Java. In
2006 Sun started to make Java available under the GNU General
Public License (GPL). Oracle continues this project called OpenJDK.
Over time new enhanced versions of Java have been released. The
current version of Java is Java 1.8 which is also known as Java 8.
Java is defined by a specification and consists of a programming
language, a compiler, core libraries and a runtime (Java virtual
machine) The Java runtime allows software developers to write
program code in other languages than the Java programming
language which still runs on the Java virtual machine. The Java
platform is usually associated with the Java virtual machine and
the Java core libraries.
The Java language was designed with the following properties:
● Platform independent: Java programs use the Java virtual
machine as abstraction and do not access the operating
system directly. This makes Java programs highly portable.
A Java program (which is standard-compliant and follows
8

certain rules) can run unmodified on all supported


platforms, e.g., Windows or Linux.
● Object-orientated programming language: Except the
primitive data types, all elements in Java are objects.
● Strongly-typed programming language: Java is
strongly-typed, e.g., the types of the used variables must be
pre-defined and conversion to other objects is relatively
strict, e.g., must be done in most cases by the programmer.
● Interpreted and compiled language: Java source code is
transferred into the bytecode format which does not depend
on the target platform. These bytecode instructions will be
interpreted by the Java Virtual machine (JVM). The JVM
contains a so-called Hotspot-Compiler which translates
performance critical bytecode instructions into native code
instructions.
● Automatic memory management: Java manages the
memory allocation and de-allocation for creating new
objects. The program does not have direct access to the
memory. The so-called garbage collector automatically
deletes objects to which no active pointer exists.
1.2 Basic
In programming languages, identifiers are used for identification purposes. In Java, an
identifier can be a class name, method name, variable name, or label. Java
is statically typed and also a strongly typed language because, in Java, each type
of data (such as integer, character, hexadecimal, packed decimal, and so forth) is
predefined as part of the programming language and all constants or variables defined
for a given program must be described with one of the data types.

Data Types in Java:


9

Java provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition checking time.
1. while loop: A while loop is a control flow statement that allows code
to be executed repeatedly based on a given Boolean condition. The
while loop can be thought of as a repeating if statement.
Syntax :

while (boolean condition)


{
loop statements...
}

Flowchart:
10

● While loop starts with the checking of condition. If it


evaluated to true, then the loop body statements are
executed otherwise first statement following the loop is
executed. For this reason, it is also called Entry control
loop
● Once the condition is evaluated to true, the statements
in the loop body are executed. Normally the statements
contain an update value for the variable being
processed for the next iteration.
● When the condition becomes false, the loop terminates
which marks the end of its life cycle.

// Java program to illustrate while loop


class whileLoopDemo
{
    public static void main(String args[])
    {
        int x = 1;
  
        // Exit when x becomes greater than 4
        while (x <= 4)
        {
            System.out.println("Value of x:" + x);
  
            // Increment the value of x for
            // next iteration
            x++;
        }
    }
}
Output:
Value of x:1
Value of x:2
Value of x:3
11

Value of x:4
2. for loop: for loop provides a concise way of writing the loop
structure. Unlike a while loop, a for statement consumes the
initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}

Flowchart:

● Initialization condition: Here, we initialize the variable


in use. It marks the start of a for loop. An already
declared variable can be used or a variable can be
declared, local to loop only.
● Testing Condition: It is used for testing the exit
condition for a loop. It must return a boolean value. It is
also an Entry Control Loop as the condition is checked
prior to the execution of the loop statements.
● Statement execution: Once the condition is evaluated
to true, the statements in the loop body are executed.
● Increment/ Decrement: It is used for updating the
variable for next iteration.
12

● Loop termination:When the condition becomes false,


the loop terminates marking the end of its life cycle.

// Java program to illustrate for loop.


class forLoopDemo
{
    public static void main(String args[])
    {
        // for loop begins when x=2
        // and runs till x <=4
        for (int x = 2; x <= 4; x++)
            System.out.println("Value of x:" + x);
    }
}
Output:
Value of x:2
Value of x:3
Value of x:4

Enhanced For loop

Java also includes another version of for loop introduced in Java 5.


Enhanced for loop provides a simpler way to iterate through the
elements of a collection or array. It is inflexible and should be used
only when there is a need to iterate through the elements in
sequential manner without knowing the index of currently processed
element.
Also note that the object/variable is immutable when enhanced for
loop is used i.e it ensures that the values in the array can not be
modified, so it can be said as read only loop where you can’t update
the values as opposite to other loops where values can be modified.
We recommend using this form of the for statement instead of the
general form whenever possible.(as per JAVA doc.)
Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
Let’s take an example to demonstrate how enhanced for loop can
be used to simplify the work. Suppose there is an array of names
and we want to print all the names in that array. Let’s see the
difference with these two examples
Enhanced for loop simplifies the work as follows-

// Java program to illustrate enhanced for loop


public class enhancedforloop
13

{
    public static void main(String args[])
    {
        String array[] = {"Ron", "Harry", "Hermoine"};
  
        //enhanced for loop
        for (String x:array)
        {
            System.out.println(x);
        }
  
        /* for loop for same function
        for (int i = 0; i < array.length; i++)
        {
            System.out.println(array[i]);
        }
        */
    }
}
Output:
Ron
Harry
Hermoine
2. do while: do while loop is similar to while loop with only difference
that it checks for condition after executing the statements, and
therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
14

Flowchart:

● do while loop starts with the execution of the


statement(s). There is no checking of any condition for
the first time.
● After the execution of the statements, and update of the
variable value, the condition is checked for true or false
value. If it is evaluated to true, next iteration of loop
starts.
● When the condition becomes false, the loop terminates
which marks the end of its life cycle.
● It is important to note that the do-while loop will execute
its statements atleast once before any condition is
checked, and therefore is an example of exit control
loop.

// Java program to illustrate do-while loop


class dowhileloopDemo
{
    public static void main(String args[])
    {
        int x = 21;
        do
        {
            // The line will be printed even
            // if the condition is false
            System.out.println("Value of x:" + x);
            x++;
        }
        while (x < 20);
    }
}
15

Output:
Value of x: 21

Pitfalls of Loops

1. Infinite loop: One of the most common mistakes while


implementing any sort of looping is that that it may not ever exit,
that is the loop runs for infinite time. This happens when the
condition fails for some reason.
Examples:
//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
    public static void main(String[] args)
    {
  
        // infinite loop because condition is not apt
        // condition should have been i>0.
        for (int i = 5; i != 0; i -= 2)
        {
            System.out.println(i);
        }
        int x = 5;
  
        // infinite loop because update statement
        // is not provided.
        while (x == 5)
        {
            System.out.println("In the loop");
        }
    }
}
2. Another pitfall is that you might be adding something into you
collection object through loop and you can run out of memory. If you
try and execute the below program, after some time, out of memory
exception will be thrown.

//Java program for out of memory exception.


import java.util.ArrayList;
public class Integer1
{
    public static void main(String[] args)
    {
        ArrayList<Integer> ar = new ArrayList<>();
        for (int i = 0; i < Integer.MAX_VALUE; i++)
        {
            ar.add(i);
        }
    }
}
16

Output:
Exception in thread "main" java.lang.OutOfMemoryError:
Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown
Source)
at java.util.ArrayList.add(Unknown Source)
at article.Integer1.main(Integer1.java:9)
17

CHAPTER 2 OOP CONCEPT-1

2.1 Classes & Object

Classes and Objects are basic concepts of Object-Oriented Programming which


revolve around the real-life entities.

A class is a user defined blueprint or prototype from which objects are created.
 It represents the set of properties or methods that are common to all objects of
one type. In general, class declarations can include these components, in
order: 
 
1. Modifiers: A class can be public or has default access.
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter
(capitalized by convention).
4. Superclass (if any): The name of the class’s parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
5. Interfaces (if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces { }.

Object is a basic unit of Object-Oriented Programming and represents the


real-life entities.  A typical Java program creates many objects, which as you
know, interact by invoking methods. An object consists of: 
 
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behaviour: It is represented by methods of an object. It also
reflects the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one
object to interact with other objects.
Example of an object: dog
 
18

Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.

2.2 Constructors

Constructors are used to initialize the object’s state. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at time of
Object creation.

Each time an object is created using new() keyword at least one constructor (it


could be default constructor) is invoked to assign initial values to the data
members of the same class.
A constructor is invoked at the time of object or instance creation. For Example:
class Geek
{
.......

// A Constructor
new Geek() {}

.......
}

// We can create an object of the above class


// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
19

Rules for writing Constructor:

● Constructor(s) of a class must have same name as the class name


in which it resides.
● A constructor in Java can not be abstract, final, static and
Synchronized.
● Access modifiers can be used in constructor declaration to control
its access i.e which other class can call the constructor.

Types of constructor

There are two type of constructor in Java:


1. No-argument constructor: A constructor that has no parameter is
known as default constructor. If we don’t define a constructor in a
class, then compiler creates default constructor (with no
arguments) for the class. And if we write a constructor with
arguments or no-arguments then the compiler does not create a
default constructor.
Default constructor provides the default values to the object like 0,
null, etc. depending on the type.
2. Parameterized Constructor: A constructor that has parameters is
known as parameterized constructor. If we want to initialize fields of
the class with your own values, then use a parameterized
constructor.

2.3 Inheritance

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the


mechanism in java by which one class is allow to inherit the features(fields and
methods) of another class.

Types of Inheritance in Java

Single Inheritance : In single inheritance, subclasses inherit the features of


one superclass. In image below, the class A serves as a base class for the
derived class B.
20

Multilevel Inheritance : In Multilevel Inheritance, a derived class will be


inheriting a base class and as well as the derived class also act as the base
class to other class. In below image, the class A serves as a base class for the
derived class B, which in turn serves as a base class for the derived class C. In
Java, a class cannot directly access the grandparent’s members.

Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a


superclass (base class) for more than one sub class.In below image, the class
A serves as a base class for the derived class B,C and D.
21

CHAPTER 3 OOP CONCEPT-2

3.1 Encapsulation

Encapsulation is defined as the wrapping up of data under a single unit. It is the


mechanism that binds together code and the data it manipulates. Other way to
think about encapsulation is, it is a protective shield that prevents the data from
being accessed by the code outside this shield.
● Technically in encapsulation, the variables or data of a class is
hidden from any other class and can be accessed only through any
member function of own class in which they are declared.
● As in encapsulation, the data in a class is hidden from other classes
using the data hiding concept which is achieved by making the
members or methods of class as private and the class is exposed to
the end user or the world without providing any details behind
implementation using the abstraction concept, so it is also known
as combination of data-hiding and abstraction.
● Encapsulation can be achieved by: Declaring all the variables in the
class as private and writing public methods in the class to set and
get the values of variables.
22

Advantages of Encapsulation:
● Data Hiding: The user will have no idea about the inner
implementation of the class. It will not be visible to the user that how
the class is storing values in the variables. He only knows that we
are passing the values to a setter method and variables are getting
initialized with that value.
● Increased Flexibility: We can make the variables of the class as
read-only or write-only depending on our requirement. If we wish to
make the variables as read-only then we have to omit the setter
methods like setName(), setAge() etc. from the above program or if
we wish to make the variables as write-only then we have to omit
the get methods like getName(), getAge() etc. from the above
program
● Reusability: Encapsulation also improves the re-usability and easy
to change with new requirements.
● Testing code is easy: Encapsulated code is easy to test for unit
testing.

3.2 Abstraction in Java


Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or the non-essentials units are not displayed to
the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The
properties and behaviours of an object differentiate it from other objects of
similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of car or applying brakes will
stop the car but he does not know about how on pressing the accelerator the
speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what
abstraction is.
23

In java, abstraction is achieved by interfaces and abstract classes. We can


achieve 100% abstraction using interfaces.

Abstract classes and Abstract methods:

1. An abstract class is a class that is declared with abstract keyword.


2. An abstract method is a method that is declared without an
implementation.
3. An abstract class may or may not have all abstract methods. Some
of them can be concrete methods
4. A method defined abstract must always be redefined in the
subclass, thus making overriding compulsory OR either make
subclass itself abstract.
5. Any class that contains one or more abstract methods must also be
declared with abstract keyword.
6. There can be no object of an abstract class. That is, an abstract
class cannot be directly instantiated with the new operator.
7. An abstract class can have parametrized constructors and default
constructor is always present in an abstract class

When to use abstract classes and abstract methods with an example

There are situations in which we will want to define a superclass that declares
the structure of a given abstraction without providing a complete implementation
of every method. That is, sometimes we will want to create a superclass that
only defines a generalization form that will be shared by all of its subclasses,
leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design
system or game simulation. The base type is “shape” and each shape has a
colour, size and so on. From this, specific types of shapes are
derived(inherited)-circle, square, triangle and so on – each of which may have
additional characteristics and behaviours. For example, certain shapes can be
flipped. Some behaviours may be different, such as when you want to calculate
the area of a shape. The type hierarchy embodies both the similarities and
differences between the shapes.
24

Encapsulation vs Data Abstraction

1. Encapsulation is data hiding (information hiding) while Abstraction is


detail hiding (implementation hiding).
2. While encapsulation groups together data and methods that act
upon the data, data abstraction deals with exposing the interface to
the user and hiding the details of implementation.

Advantages of Abstraction

1. It reduces the complexity of viewing the things.


2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only
important details are provided to the user.
25

CHAPTER 4 JAVA GENERICS

4.1 Generics Introduction


Generics means parameterized types. The idea is to allow type (Integer,
String, … etc, and user-defined types) to be a parameter to methods, classes,
and interfaces. Using Generics, it is possible to create classes that work with
different data types.
26

An entity such as class, interface, or method that operates on a


parameterized type is called generic entity.

Object is the superclass of all other classes and Object reference can refer to
any type object. These features lack type safety. Generics adds that type safety
feature. We will discuss that type safety feature in later examples.
Generics in Java is similar to templates in C++. For example, classes like
HashSet, Array List, HashMap, etc use generics very well. There are some
fundamental differences between the two approaches to generic types.

Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To
create objects of generic class, we use following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()

Note: In Parameter type we can not use primitives like


'int','char' or 'double'.

Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use
for any type we want.
.
2. Type Safety : Generics make errors to appear compile time than at
run time (It’s always better to know problems in your code at
compile time rather than making your code fail at run time).
Suppose you want to create an ArrayList that store name of
students and if by mistake programmer adds an integer object
instead of string, compiler allows it. But, when we retrieve this data
from ArrayList, it causes problems at runtime.
27

You might also like