week1
week1
TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P
WEEK 1
Introduction to Java
Java is a general-purpose, object-oriented programming language developed by “SUN
MICROSYSTEM” of USA in 1991. It was designed as the consumer of the base language
C and C++. Java is a simple, reliable, portable and powerful language.
The most special about java as compared to other programming language is that you can
write special programs called “APPLETS” that can be downloaded from the internet and
played safely within a web browser.
Java is an Object-Oriented programming language.
Purpose is to create a new language that would allow consumer electronic devices to
communicate with each other.
Writing software program which works on hardware/electronics devices.
For internet programming(Applet programs)
The team initiated this project to develop a language for digital devices such set-top
boxes, television, Washing Machine ,Kitchen appliances etc.
Java code looks like C, C++, or C#, but code written in those languages will not work
in Java in most cases without being changed.
Java History
Java was created at Sun Microsystems.
Java was originally developed by James Gosling , Patrick Naughton and their team
in the early 1991s.
Java which was called Oak when it was still being developed. The name Oak was
used by Gosling after an oak tree that stood outside his office.
Why “Oak”?
The name Oak was used by Gosling after an oak tree that remained outside his office.
Also, Oak is a national tree of numerous nations like the U.S.A., France, Germany,
Romania, etc. But they had to later rename it as “JAVA”.
Why ‘’JAVA’’
Gosling and his team did a brainstorm session and after the session, they came up
with several names such as JAVA, DNA, SILK, RUBY, etc.
Java name was decided after much discussion since it was so unique. The name Java
originates from a sort of espresso bean, Java. Gosling came up with this name while
having a coffee near his office.
Java Features
1. Compiled and Interpreted
2. Platform-Independent and portable
3. Object-Oriented
4. Robust and Secure
5. Distributed
6. Simple, small and familiar
7. Multithreaded and Interactive
8. High Performance
9. Dynamic and Extensible
10. Architecture-neutral
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
Java code is compiled by the compiler and converted into byte code. This byte code is a
platform-independent code because it can be run on multiple platforms i.e. Write Once and
Run Anywhere(WORA). Also the size of the primitive data types are machine independent.
Portable :We may carry the java byte code to any platform.
Java Architecture
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates
the process of interpretation and compilation. It defines all the processes involved in
creating a Java program. Java Architecture explains each and every step of how a program
is compiled and executed.
The following figure represents the Java Architecture in which each step is elaborate
graphically.
JVM, JRE, and JDK are platform dependent because the configuration of each OS is
different from each other. These are three main components of Java Architecture. The
execution of a program is done with all these three components. However, Java is platform
independent.
Java Virtual Machine
The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The
feature states that we can write our code once and use it anywhere or on any operating
system. Our Java program can run any of the platforms only because of the Java Virtual
Machine. It is a Java platform component that gives us an environment to execute java
programs. JVM's main task is to convert byte code into machine code.
JVM, first of all, loads the code into memory and verifies it. After that, it executes the code
and provides a runtime environment.
The java compiler produces an intermediate code known as byte code for a machine that
doesn’t exist. This machine is called java virtual machine (It exists only inside computer
memory).It is a computer within a computer and does all major functions of a real computer.
That is why java is portable and platform independent.
Process of compilation
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
The virtual machine code is not machine specific .The machine specific code generated by
the java interpreter by acting as an intermediate between virtual machine and real machine.
The below figure illustrates how java works on a typical computer.
JVM (Java Virtual Machine) is an abstract machine.
It is called a virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can
be executed.
It can also run those programs which are written in other languages and compiled to
Java bytecode.
JVMs are available for many hardware and software platforms.
The virtual machine code is not machine specific .The machine specific code
generated by the java interpreter.
1)JVM(Java Virtual Machine): The java compiler produces an intermediate code known
as bytecode for a machine that doesn’t exist. That is why java is portable and platform
independent. The virtual machine code is not machine specific .The machine specific code
generated by the java interpreter by acting as an intermediate between virtual machine and
real machine.
2)set of libraries (rt.jar): Stands for runtime and contains all of the compiled class files for
the core Java Runtime environment.
3)Other files: other files that JVM uses at runtime.
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as
an interpreter/loader (java), a compiler (javac), an archive (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
Java development kit is the core component of java environment and provides all the tools,
executable and libraries required to compile, debug and execute a java program. JDK is a
superset of JRE since it contains JRE with java compiler, debugger and core classes.
JDK comes with a collection of development tools that are used for developing running java
programs. They include:
1. javac—Java compiler, which translates java source code to byte code.
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source
code into byte code.
2. java—Java interpreter, which translates byte code to machine code & then executes.
3. appletviewer—It is used to run java applets. The applet viewer creates a window in
which the applet can be viewed. It provides complete support for all applet functions,
including networking and multimedia capabilities.
4. JDB—Java debugger, which helps us to find errors in our programs. Java debugger is a
command-line debugger used to monitor the execution of java programs in support of
debugging and test activities.
5. javah—Java header file generation tool, used while executing “Native Methods”. It
produces both header and source files. The header file contains C-language definitions that
map to java class definitions. The source files contain the C functions that map to class
methods.
6. Javap—Java disassembler, converts byte code to source code.
7. Javadoc—Java documentation. It creates HTML format documentation from java source
code that document packages and classes, including methods and data fields. A doc-
comment block begins with the characters /** and ends like a normal C comment.
Environment variable PATH should be set to point to where the Java binaries
have been installed. Refer to your shell documentation, if you have trouble doing
this.
Example, if you use bash as your shell, then you would add the following line to
the end of your '.bashrc: export PATH = /path/to/java:$PATH'
Popular Java Editors
To write your Java programs, you will need a text editor. There are even more sophisticated
IDEs available in the market. But for now, you can consider one of the following −
Notepad − On Windows machine, you can use any simple text editor like Notepad
(Recommended for this tutorial), Text Pad.
Netbeans − A Java IDE that is open-source and free which can be downloaded
from https://www.netbeans.org/index.html.
Eclipse − A Java IDE developed by the eclipse open-source community and can be
downloaded from https://www.eclipse.org/.
Rules of Identifier
1. It must start with a letter or underscore (-)
2. They must not begin with digit.
3. Space or any special characters are not allowed.
4. Uppercase & lowercase letters are distinct.
5. It can be of any length.
3. Literalsliterals are a sequence of characters that represent constant values to be
stored in variables. It includes integer literals, real literals, character literals, string
literals and Boolean literals.
integer literals: any whole number is an integer literal.Example:1,5,7
real literals: real constants represents decimal values with a fraction part.
Example: 12.0, 0.5577,12E+50
SeparatorsSeparators are symbols used to indicate where groups of code are divided &
arranged. They inform the compiler of how things are grouped in the code.Items in the list
are separated by commas.
Example:1. Parentheses ( ) : Used to enclose parameters in method definition and
invocation.
2.Braces { } : Used to contain the values of automatically initialized arrays and to
define a block of code for classes , methods and local scopes.
3. Brackets [ ] : Used to declare array types and for dereferencing array values.
4.Semicolon ; : Used to separate statements.
5. Period . : Used to separate package names from sub-package and classes.
A java program may contain many classes of which only one class contain a main()
definition.
Classes contain data members and methods that operate on the data members. To write a
java program , we first define classes and then put them together . Java program may
contain one or more sections as shown below.
The general structure of java program is as follows.
like to refer to a later stage. Java supports three types of comments (line ,block and
documentation).
2. Package Declaration The first statement allowed in a java file is a package statement.
This statement declares a package name and informs the compiler that the classes defined
here belongs to the package .“package” is a keyword & used to create user defined package.
The general syntax is package package name.
3.Import Statement java environment contains JDK tools & API package. Import
statements are used to access built in classes & methods.(similar to #include statements in
example: import java.lang.*;
4. Interface Statement An interface is like a class but includes a group of method
declarations. This also an optional section and is used only when we wish to implement the
multiple inheritance features in the program.
5. Class Definition A java program may contain multiple class definitions classes are the
primary and essential elements of a java program . These classes are used to map the objects
of real world problems. This includes class name, visibility modes, variables name &
methods.
6. main() method class The main method creates objects of various classes and
establishes communication between them. Java programs requires main () function. The
program execution start with main () function.
Compilation and execution of java program
java is a two-stage system.
• In the first stage, java complier translates source code into byte code.
• In the second stage, java interpreter converts java byte code into machine code(object
code) that can be directly executed by the machine.
Text Editor
Java c
Header files
Java . class file Java h
Java JDB
The following are the steps that illustrate execution process of the application program
The user creates the java source code in the text editor say notepad/ Java IDE by the
eclipse/any other editors
The source code is compiled with Javac command.
javadoc tool can be used to create HTML format documentation from java source
Code.
On compiling the source code a .class file gets generated which consists of the byte
code.
The developer may use javah tool for generating the required header files.
The class file produced by javac can be interpreted using java in order to produce
executable fie.
Class Names − For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in Upper
Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should be
in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class
name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name do
not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then
file name can be different than class name. It is also not mandatory to have a public class in
the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
2. Best Practices
In recent years, software best practices like unit testing, TDD, CI, etc. have been growing
very fast in terms of adoption. These practices elevate code quality and maintainability.
Implementing clean code principles is a foundational skill that pays off especially well
when it’s time to refactor code or bring code under testing. Clean code makes it easier to
read and test. If you think of it as part of a house, clean code is the foundation.
3. Logic Behind the Code
If someone asks you about your code quality, you should provide a rational justification. If
you’ve never methodically considered the quality of your coding style, there’s likely plenty
of opportunity for improvement. Those who write clean code have concrete activities,
patterns, and techniques they use to keep their code clean.
4. Maintenance
Writing code is relatively easy, reading is hard. This is why so many developers prefer to
rewrite rather than do the hard work of reading and comprehending existing code. By
writing code that is readable, you are optimizing for the 90% of the time we are reading
code, rather than the 10% of the time you are writing it. This is a significantly more cost-
effective strategy than the alternative strategy of writing code as quickly as possible without
concern for the readability of the code. By creating code that is maintainable, you are
optimizing the majority of your time and the cost of maintaining code.
5. Easy to Test
By building clean code, automated testing of that code is encouraged. By automated testing,
I mean Test-Driven Development - which is the most effective way to improve the quality
of code, improve the long-term velocity of a team, and reduce the number of software
defects. All of these factors contribute heavily to the overall ROI of the software.
6. Simplicity
Keep your code as simple and readable as possible. Don’t over-complicate problems, which
is a common issue among software developers. By keeping it simple, you can produce
higher quality code, solve problems faster ,and work better in groups.The KISS principle
(keep it simple, stupid), as well as the DRY principle, which means don’t repeat yourself. It
allows software developers to avoid duplication and allows them to produce much cleaner
code compared to the programmer who uses unnecessary repetition.And don’t add extra
features because you might need them in the future. Never do that. It’s a useless waste of
time and money.
7. Consistency
Indentation in the code is much like the arrangement that you need in a supermarket. When
your code is indented, it becomes more readable and easier to find what you’re looking for.
Especially when you pay attention to the names of the items. Having a proper naming
convention is extremely important in code for future edits. naming elements on the basis of
what they are is a common rule helps a lot. It creates consistency and makes it easier
to come back and work on the project at a later time.
8. Cost Savings
By doing clean code, you gain all those advantages listed above, and all of them lead to cost
savings.
Mathematical Function
The functions are defined in java.lang.Math package contains methods for performing basic
numeric operations such as the elementary exponential, logarithm, square root and
trigonometric functions. To make use of these functions we need to write the following
statement.
Import java.lang.Math; This allows access of mathematical functions defined in Math class
of java. Following are some of the Math class methods.
Function Meaning
sqrt(x) Returns the square root of x.
pow(x,y) Returns x raised to y (xy)
max(a,b) Returns the maximum of a&b
min(a,b) Returns the minimum of a&b
abs(x) Returns absolute value of long x
exp(x) Returns e raised to x (ex)
Rules of Identifier
1. It must start with a letter or underscore (-)
2. They must not begin with digit.
3. Space or any special characters are not allowed.
4. Uppercase & lowercase letters are distinct.
5. It can be of any length.
6. Literalsliterals are a sequence of characters that represent constant values to be
stored in variables. It includes integer literals, real literals, character literals, string
literals and Boolean literals.
integer literals: any whole number is an integer literal.Example:1,5,7
real literals: real constants represents decimal values with a fraction part.
Example: 12.0, 0.5577,12E+50
character literals: A literal character is represented inside a pair of single quotes.All
of the visible ASCII characters can be entered inside the quotes.
Example: ‘a’, ‘$’, ‘@’
string literals:A string literals are sequence of characters enclosed between pair of
double quotes.
Example: “hello”
boolean literals: there are two Boolean literal true and false. They can be used in an
expression with Boolean operators.
OperatorsAn operator is a symbol that takes one or more arguments & operators on them
to produce a result. There are many types of operators in java such as unary operator.
SeparatorsSeparators are symbols used to indicate where groups of code are divided &
arranged. They inform the compiler of how things are grouped in the code.Items in the list
are separated by commas.
Example:1. Parentheses ( ) : Used to enclose parameters in method definition and
invocation.
2.Braces { } : Used to contain the values of automatically initialized arrays and to
define a block of code for classes , methods and local scopes.
3. Brackets [ ] : Used to declare array types and for dereferencing array values.
4.Semicolon ; : Used to separate statements.
5. Period . : Used to separate package names from sub-package and classes.
Symbolic constant
Q: Illustrate and explain symbolic constants.
When constants appear repeatedly in number of places in the program symbolic constants
can be used.In java, the symbolic constants can be created using “final” keyword.
The general syntax of creating a symbolic constant.
final data types symbolic name= value;
Ex:- final int pie=3.14;
final int pass_mark=35
Type casting
Q: Discuss type conversion. Explain different types of type conversions.
The type process of converting one data type to another is called casting.
The syntax is
Data type variable1= (type) variable2;
For Ex:- conversion from double to int.
double d=50.345;
int n=(double)d;
Note:The destination type is larger than the source type automatic conversion is done
byte b=78;
int a=b;