Satyam Report - Java
Satyam Report - Java
“JAVA”
BACHELOR OF TECHNOLOGY
in
“Computer Science & Engineering”
Submitted by
Satyam Dwivedi
(Roll No.1901200100098)
Submitted To
Mr. Nitin Dixit
(Assistant Professor)
This is certified that the work which is being presented in the mini project entitled
carried out during the semester under the supervision of “Great Learning”.
The matter presented in this mini project has not been submitted by me for the award
. Satyam Dwivedi
This is to certify that the above statement made by the candidate is correct to the best of
my knowledge.
ii
iii
ABSTRACT
Writing graphics 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. Both the AWT (abstract windowing toolkit) and Swing provide such
a framework.
In this report, we designed and developed a simple painter project used to enable a user to
draw any shape and any integrated graphic with any color using FreeHand (move the mouse
using your hand to draw any shape and specify the coordinate in J Panel). Several tools such
as Undo and Redo process, Clear J Panel, Set Background Color & set Foreground Color,
Save paint(Panel) to file ( *. JPG; *. GIF;*.*), and Open paint from image file are considered.
The purpose of this project is to give you practice with graphical user interface programming
in Java.
This project implemented using the components from Java's awt and swing library in the
Java programming language (NetBeans IDE7.2.1). As the final result of our project is
enabling you to use FreeHand to draw as an easy way to draw the Circle, Line, Rectangle,
Square, and Oval, and integrated graphics such as a car, a street, a football stadium, traffic
signals and others.
iv
. ACKNOWLEDGEMENT
I am sincerely thankful to Mr. Ashutosh Rao (HOD) & Mr. Nitin Dixit (Mini
Project Coordinator) for his support. I express my gratitude and thanks to all the faculties and
staff members of Computer Science & Engineering department for their sincere cooperation
in furnishing relevant information to complete this mini project report well in time
successfully.
Finally, my greatest debt is to my parents, my family for their enduring love, support
and forbearance during my project work.
Satyam Dwivedi
Roll No.190120010009
v
TABLE OF CONTENTS
Page No.
Declaration ii
Certificate iii
Abstract iv
Acknowledgement vi
Dedication(optional) vii
List of Tables viii
List of Figures xv
List of Symbols and Abbreviations xxiii
vi
CHAPTER 3 : DECISION MAKING IN JAVA
3.1 JAVA SELECTION STATEMENT 18
4.4 INHERITENCE 29
CONCLUSION 32
REFERENCES 33
vii
CHAPTER 1
INTRODUCTION TO JAVA
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems'.
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java
and its widespread popularity, multiple configurations were built to suit various types of
platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is
guaranteed to be Write Once, Run Anywhere.
James Gosling initiated Java language project in June 1991 for use in one of his many set-
top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside
Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java,
from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once,
Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under
the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-
source, aside from a small portion of code to which Sun did not hold the copyright.
1
After the name OAK, the team decided to give a new name to it and the suggested words
were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and
fun to say, but they all wanted the name to reflect the essence of technology. In accordance
with James Gosling, Java the among the top names along with Silk, and since java was a
unique name so most of them preferred it.
Java is the name of an island in Indonesia where the first coffee(named java coffee) was
produced. And this name was chosen by James Gosling while having coffee near his office.
Note that Java is just a name, not an acronym.
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three
execution phases of a program. They are written, compile and run the program.
• The compilation is done by the JAVAC compiler which is a primary Java compiler
included in the Java development kit (JDK). It takes Java program as input and
generates bytecode as output.
• In the Running phase of a program, JVM executes the bytecode generated by the
compiler.
Now, we understood that the function of Java Virtual Machine is to execute the bytecode
produced by the compiler. Every Operating System has a different JVM but the output they
produce after the execution of bytecode is the same across all the operating systems. This is
why Java is known as a platform-independent language.
2
3. Java Development Kit(JDK): While we were using the term JDK, when we learn about
bytecode and JVM . So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment (JRE), java debuggers,
java docs, etc. For the program to execute in java, we need to install JDK on our computer in
order to create, compile and run the java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our
computers allows the java program to run, however, we cannot compile it. JRE includes a
browser, JVM, applet supports, and plugins. For running the java program, a computer needs
JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect
that memory JVM has a program called Garbage Collector. Garbage Collectors can recollect
the of objects that are not referenced. So Java makes the life of a programmer easy by
handling memory management. However, programmers should be careful about their code
whether they are using objects that have been used for a long time. Because Garbage cannot
recover the memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look
for .class files to load. By default, JDK provides many libraries. If you want to include
external libraries they should be added to the classpath.
3
Fig 1.1 Java Environment.
1. Platform Independent: Compiler converts source code to bytecode and then the JVM
executes the bytecode generated by the compiler. This bytecode can run on any platform be
it Windows, Linux, macOS which means if we compile a program on Windows, then we can
run it on Linux and vice versa. Each operating system has a different JVM, but the output
produced by all the OS is the same after the execution of bytecode. That is why we call java
a platform-independent language.
• Abstraction
• Encapsulation
4
• Inheritance
• Polymorphism
3. Simple: Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, Explicit memory allocation.
4. Robust: Java language is robust that means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible, that is why the java compiler is
able to detect even those errors that are not easy to detect by another programming language.
The main features of java that make it robust are garbage collection, Exception Handling,
and memory allocation.
5. Secure: In java, we don’t have pointers, and so we cannot access out-of-bound arrays i.e
it shows Array Index Out Of Bound Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow is impossible to exploit in Java.
8. Portable: As we know, java code written on one machine can be run on another machine.
The platform-independent feature of java in which its platform-independent bytecode can be
taken to any platform for execution makes java portable.
9. High Performance: Java architecture is defined in such a way that it reduces overhead
during the runtime and at some time java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those methods that are called
making applications to execute faster.
5
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add
classes, new methods to existing classes and even creating new classes through sub-classes.
Java even supports functions written in other languages such as C, C++ which are referred to
as native methods.
11. Sandbox Execution: Java programs run in a separate space that allows user to execute
their applications without affecting the underlying system with help of a bytecode verifier.
Bytecode verifier also provides additional security as it’s role is to check the code for any
violation access.
12. Write Once Run Anywhere: As discussed above java application generates ‘.class’ file
which corresponds to our applications(program) but contains code in binary format. It
provides ease t architecture-neutral ease as bytecode is not dependent on any machine
architecture. It is the primary reason java is used in the enterprising IT industry globally
worldwide.
13. Power of compilation and interpretation: Most languages are designed with purpose
either they are compiled language or they are interpreted language. But java integrates arising
enormous power as Java compiler compiles the source code to bytecode and JVM executes
this bytecode to machine OS-dependent executable code.
• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
• Classes
• Objects
• Instance
6
• Method
• Message Passing
• Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance
of a class.
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields
and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
Classes in Java
Example
7
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
• Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.
• Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
• Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In
the above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into
classes of the Java Language.
Constructors
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
8
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
1.5 Constructors
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
Example:1
As mentioned previously, a class provides the blueprints for objects. So basically, an object
is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
9
• Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
10
CHAPTER 2
Basic Data and Variables Types
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java −
• A primitive data type specifies the size and type of variable values, and it has no
additional methods.
11
long 8 bytes Stores whole numbers from -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Numbers
• Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends
on the numeric value.
• Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
Integer Types
▪ Byte :
The byte data type can store whole numbers from -128 to 127. This can be used instead
of int or other integer types to save memory when you are certain that the value will be
within -128 and 127:
Example:
12
byte myNum = 100;
System.out.println(myNum);
▪ Short
The short data type can store whole numbers from -32768 to 32767:
Example
System.out.println(myNum);
▪ Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general,
and in our tutorial, the int data type is the preferred data type when we create variables with
a numeric value.
Example
System.out.println(myNum);
▪ Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Example
13
You should use a floating point type whenever you need a number with a decimal, such
as 9.99 or 3.14515.
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that
you should end the value with an "f":
Example
System.out.println(myNum);
▪ Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you
should end the value with a "d":
Example
System.out.println(myNum);
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with
an uppercase letter.
14
• The size of a primitive type depends on the data type, while non-primitive types have
all the same size.
Unlike C/C++, Java strings are not terminated with a null character.
Below is the basic syntax for declaring a string in Java programming language.
Syntax:
2.3 Operators
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are---
Example:
➢ Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
15
▪ + :Unary plus, indicates positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is byte, char, or short. This is called unary numeric promotion.
➢ ++ :Increment operator, used for incrementing the value by 1. There are two varieties
of increment operator.
• Post-Increment: Value is first used for computing the result and then
incremented.
• Post-decrement : Value is first used for computing the result and then
decremented.
• +=, for adding left operand with right operand and then assigning it to variable
on the left.
• -=, for subtracting left operand with right operand and then assigning it to
variable on the left.
• *=, for multiplying left operand with right operand and then assigning it to
variable on the left.
• /=, for dividing left operand with right operand and then assigning it to variable
on the left.
16
• %=, for assigning modulo of left operand with right operand and then assigning
it to variable on the left.
➢ Relational Operators : These operators are used to check for relations like equality,
greater than, less than. They return boolean result after the comparison and are
extensively used in looping statements as well as conditional if else statements.
• ==, Equal to : returns true if left hand side is equal to right hand side.
• !=, Not Equal to : returns true if left hand side is not equal to right hand side.
• <, less than : returns true if left hand side is less than right hand side.
• <=, less than or equal to : returns true if left hand side is less than or equal
to right hand side.
• >, Greater than : returns true if left hand side is greater than right hand side.
• >=, Greater than or equal to: returns true if left hand side is greater than or
equal to right hand side.
➢ Logical Operators : These operators are used to perform “logical AND” and “logical
OR” operation, i.e. the function similar to AND gate and OR gate in digital
electronics. One thing to keep in mind is the second condition is not evaluated if the
first one is false.
• &&, Logical AND : returns true when both conditions are true.
17
➢ Bitwise Operators : These operators are used to perform manipulation of individual
bits of a number. They can be used with any of the integer types. They are used when
performing update and query operations of Binary indexed tree.
• &, Bitwise AND operator: returns bit by bit AND of input values.
➢ Shift Operators : These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively. They can be used
when we have to multiply or divide a number by two.
• <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids
left as a result. Similar effect as of multiplying the number with some power of
two.
• >>, Signed Right shift operator: shifts the bits of the number to the right and fills
0 on voids left as a result. The leftmost bit depends on the sign of initial number.
Similar effect as of dividing the number with some power of two.
Type casting is when you assign a value of one primitive data type to another type.
byte -> short -> char -> int -> long -> float -> double
18
CHAPTER 3
Decision Making in Java
These statements allow you to control the flow of your program’s execution based upon
conditions known only during run time.
19
Flowchart:
▪ If – else : The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if~
we want to do something else if the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
20
// condition is false
}
▪ Nested – if: A nested if is an if statement that is the target of another if or else. Nested if
statements means an if statement inside an if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
21
Fig 3.3 Flow chart of Nested – if.
• If – else – if : Here, a user can decide among multiple options.The if statements are
executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be
executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
22
Fig 3.4 If – else – if Flowchart.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
……. .
case valueN:
statementN;
break;
23
default:
statementDefault; }
▪ jump: Java supports three jump statement: break, continue and return. These three
• To exit a loop.
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
24
Fig 3.6 :Flowchart of Break Statement.
25
Fig
3.7 Flowchart for continue.
26
Chapter :4
Object Orientation Programming Concept in Java
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter
development time
4.1 Access Modifier: Defines access type of the method. In Java, there 4 type of the access
specifiers.
• The return type: The data type of the value returned by the method or void if does
not return a value.
27
• Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
• Parameter list: Comma separated list of the input parameters are defined, preceded
with their data type, within the enclosed parenthesis. If there are no parameters, you
must use empty parentheses ().
• Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).
• Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations.
28
Fig 4.1 OOPs Concept.
4.2 Abstraction
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. 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.
4.3 Encapsulation
It 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. Another 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, so it is also known
as data-hiding.
• 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.
29
4.4 Inheritence
• Super Class: The class whose features are inherited is known as superclass(or a base
class or a parent class).
• Sub Class: The class that inherits the other class is known as subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
4.5 : Polymorphism
It refers to the ability of OOPs programming languages to differentiate between entities with
the same name efficiently. This is done by Java with the help of the signature and declaration
of these entities. Polymorphism in Java are mainly of 2 types:
1. Overloading
2. Overriding
Method:
A method is a collection of statements that perform some specific task and return the
result to the caller. A method can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java, every method
must be part of some class that is different from languages like C, C++, and
Python. Methods are time savers and help us to reuse the code without retyping the
code.
Modifiers are divided into two groups:
30
1. Access Modifiers controls the access level
2. Non-Access Modifiers do not control access level but provide other functionality.
31
CONCLUSION
This report presents an introduction to Java and how Java is used to build graphics and what
are the tools that can be used to develop graphics and drawing required shapes.
This was an introduction to the main goal of our report that presented that is design and
development a simple Painter project used to draw any shape (Circle, Line, Rectangle,
Square, and Oval using FreeHand, Undo and Redo process, Clear JPanel, Set Background
Color & set
Foreground Color, Save paint (Panel) to file ( *. JPG; *. GIF; *.* ), and Open paint from
image file are considered. The system enables you to use Free Hand to draw (move the
mouse using your hand to draw any shape and specify the coordinate in JPanel) as an easy
way to draw the integrated paint, for example, a car , a street , a football stadium , traffic
signals and others.
32
References
1. https://www.learnjavaonline.org/
2. https://www.codecademy.com/learn/learn-java
3. https://www.java67.com/2018/06/21-websites-to-learn-how-to-code-for.html
4. https://www.tutorialspoint.com/java/index.htm
5. https://www.freecodecamp.org/news/learn-java-free-java-courses-for-beginners/
6. https://www.javatpoint.com/java-tutorial
33