0% found this document useful (0 votes)
53 views

week1

The document provides an overview of Java, an object-oriented programming language developed by Sun Microsystems in 1991, highlighting its history, evolution, features, and architecture. Key features include its platform independence, robustness, security, and support for multithreading. The document also explains the components of Java architecture, including the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with instructions for setting up a local Java programming environment.

Uploaded by

9gnxfs7qvx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

week1

The document provides an overview of Java, an object-oriented programming language developed by Sun Microsystems in 1991, highlighting its history, evolution, features, and architecture. Key features include its platform independence, robustness, security, and support for multithreading. The document also explains the components of Java architecture, including the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with instructions for setting up a local Java programming environment.

Uploaded by

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

Dr.

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.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

Evolution of java language


Q: Briefly explain the evolution of java language
 Java was developed by James Gosling and Patrick Naughton at Sun Microsystems in
June 1991.
 1990-sun Microsystems decided to develop special software and also appointed
“James Gosling has a team leader.
 1991-The team was developed new language called “OAK”.
 1992-Demontrated the application of “OAK” language.
 1993-Team develops “Web Applets” using “OAK” language and run on internet
(World Wide Web).
 1994-The team was developed a web browser called “Hot Java” to run applet
programs on internet.
 1995-“OAK” was renamed “Java”.
 1996-Team release “Java Development Kit” (JDK 1.0).
 1997-Team release “Java Development Kit” (JDK 1.1).
 1998-Team release “Java Development Kit” (JDK 1.2) and software development kit
(SDK1.2).
 1999-Team release Java 2 platform, standard Edition (J2SE) and enterprise
edition(J2EE).
 2000-J2SE with SDK 1.3 was released.
 2002- J2SE with SDK 1.4 was released.
 2004- J2SE with JDK 5.0 was released.

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

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

1. Compiled and Interpreted


Usually a computer language is either complied or interpreted. Java combines both these
approaches thus making java 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.
2.Simple, small and familiar
Java is a small and simple language its syntax is based on C++. For example , java does not
use pointers, pre-processor header files ,goto statement and many others. It also eliminates
operator overloading and multiple inheritance. Familiarity is another striking feature of java
Java uses many constructs of C and C++ and therefore, java code looks like c++ code.
3.Platform Independent and portable
Q: Java is platform independent language. Justify.
A platform is the hardware or software environment in which a program runs.
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 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.

4. Object-Oriented: Object-oriented means we organize our software as a combination of


different types of objects that incorporates both data and behaviour. Java is a true object
oriented language. Almost everything in java is an object. All program code and data reside
within objects and classes. Java comes with extensive set of classes arranged in packages.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules. Basic concepts of OOPs are: Object,
Class , Inheritance, Polymorphism, Abstraction, Encapsulation

5. Robust and Secure

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

Q: Discuss how java is more secured than other language.


Java is secured because:
 No explicit pointer
 Java Programs run inside virtual machine
 Class loader: adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
 Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
 Security Manager: determines what resources a class can access such as reading
and writing to the local disk.
Robust
Java is a robust language uses strong memory management. It provides many safeguards to
ensure reliable code. There is lack of pointers that avoids security problem. There is
automatic garbage collection in java. There is exception handling and type checking
mechanism in java. All these points make java robust.
6. Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. This enables multiple programmers at multiple
remote locations to collaborate and work together in a single project.
7.Multi-threaded and Interactive
Q: Give the definition of multithreading. Discuss how multithreading improves the
performance of java.
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
Multithreading means handling multiple tasks simultaneously. Java supports multithreaded
programs. This means that we need not wait for the application to finish one task before
beginning another.
8. High-performance
Java is faster than traditional interpretation since byte code is "close" to
native .Incorporation of multithreading enhances the overall execution speed of java
programs.
9. Dynamic and Extensible
Java is a dynamic language supports dynamically linking of new class libraries ,methods
and objects .java program supports functions written in other languages such as C and C++.
These functions are known as “native methods “.
10.Architecture-neutral
There is no implementation dependent features e.g. 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. But in java, it occupies 4 bytes of memory for both 32
and 64 bit architectures.

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.

Java Architecture can be explained by using the following steps:

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

 There is a process of compilation and interpretation in Java.


 Java compiler converts the Java code into byte code.
 After that, the JVM converts the byte code into machine code.
 The machine code is then executed by the machine.

The following figure represents the Java Architecture in which each step is elaborate
graphically.

Components: JVM, JRE, JDK; Applications


Components of Java Architecture
The Java architecture includes the three main components:
 Java Virtual Machine (JVM)
 Java Runtime Environment (JRE)
 Java Development Kit (JDK)

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

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

 Provides runtime environment

Process of converting byte code into the machine 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.

Java Runtime Environment(JRE)


 JRE is an acronym for Java Runtime Environment.
 It is also written as Java RTE.
 The Java Runtime Environment is a set of software tools which are used for
developing Java applications.
 It provides an environment in which Java programs are executed.
 JRE takes our Java code, integrates it with the required libraries, and then starts the
JVM to execute it.
It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that
JVM uses at runtime. It consists of

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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.

Java Development Kit


It is a software development environment used in the development of Java applications and
applets. Java Development Kit holds JRE, a compiler, an interpreter or loader, and several
development tools in it. It physically exists. It contains JRE + development tools.

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.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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.

Java environment setup


 Local Environment Setup
 If you are still willing to set up your environment for Java programming language,
then this section guides you on how to download and set up Java on your machine.
Following are the steps to set up the environment.
 Java SE is freely available from the link Download Java. You can download a
version based on your operating system.
 Follow the instructions to download Java and run the .exe to install Java on your
machine. Once you installed Java on your machine, you will need to set
environment variables to point to correct installation directories −
 Setting Up the Path for Windows
 Assuming you have installed Java in c:\Program Files\java\jdk directory −
 Right-click on 'My Computer' and select 'Properties'.
 Click the 'Environment variables' button under the 'Advanced' tab.
 Now, alter the 'Path' variable so that it also contains the path to the Java
executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32',
then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program
Files\java\jdk\bin'.
 Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

 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/.

Q: What is a token? List the different types of tokens supported by java.


Q: 1.Define the following
a. Keywords
b. Literals
2. Define the following
a. Identifiers
b. Separators
The smallest individual unit of the java program is called tokens
Types of tokens in Java
1. Reserved word
2. Identifiers
3. Literals
4. Operators
5. Separators
1. Reserved word or Keywords:
Keywords are an essential part of a java language. These keywords cannot used to name
variable or class .Some of the keywords are final, static, super, implements, extends,
class,int ,try ,catch,throw stc.

Q: Define the term identifier. Give an example.


2. Identifiers identifiers are used for naming variables, classes, methods, objects etc.

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. Literalsliterals 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

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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.
OperatorsAn 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.

SeparatorsSeparators 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.

Structure of java program


Java program structure
Q:List the different sections of java program structure.
Q:Explain the typical structure of java program

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.

1. Documentation section  The documentation section includes a set of comment lines


giving the name of the program, the author and other details, which the programmer would

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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.

The process of building and running java application programs.

Text Editor

Java Source code Java Doc HTML Files

Java c

Header files
Java . class file Java h

Java JDB

Java program output


Aparna Nayak L/CS
Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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.

The requirement for Java Hello World Example


For executing any Java program, the following software or application must be properly
installed.
• Install the JDK .
• Set path of the jdk/bin directory
• Create the Java program
• Compile and run the Java program

Creating Hello World Example


• Using Notepad

Let's create the hello java program

Using eclipse Editor:


Create a NewProject

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in Java.
• public keyword is an access modifier that represents visibility. It means it is visible to
all.
• static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main() method is executed by the JVM, so it
doesn't require creating an object to invoke the main() method. So, it saves memory.
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args or String args[] is used for command line argument. We will discuss it
in coming section.
• System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class. We will
discuss the internal working of System.out.println() statement in the coming section.
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have different meaning in Java.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

 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.

Clean coding in java


What Is Clean Code?
When we talk about clean code, we talk about a reader-focused development style that
produces software that’s easy to write, read, and maintain. Clean code is code that is easy
to understand and easy to change.
• Your code should be as efficient, readable, and maintainable as possible, and instead
of only solving the problem. The code is easy to read, whether that reader is the
original author of the code or somebody else.
• Your code should be understandable, should be clean. you should always put a bit of
extra time in to focus on the design of your code, on architecture.
• It is extremely important to have the ability to easily extend and refactor your code.
changes introduced in the code do not break any existing functionality.
• There shouldn’t be doubts and misunderstandings.
• For the code to be easy to change, you need to be sure that you took into account that
classes and methods are small and only have a single responsibility.
• classes and methods are predictable and work as expected.
• The code is easily testable and has unit tests, that tests are easy to understand and easy
to change, etc.

Reasons Why Clean Code Matters


1. Clearness
Each developer should take care of the code and make it as clean and clear as possible.
Developers are like authors, great authors are known for writing books that tell a clear,
compelling story. They use chapters, headings, and paragraphs to clearly organize their
thoughts and painlessly guide their reader. Developers work in a very similar system, but
use namespaces, classes, and methods instead of words.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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)

Q:Write a simple java program to illustrate the use of mathematical function.


import java.lang.Math;
class mathfun
{

public static void main (String arg[])


{
double x=5,y;
int a=5,b=10;
y=Math.sqrt(x);
System.out.println(“Square=”+y);
y=Math.pow(x,2);
System.out.println(“power=”+y);
int m=Math.max(a,b);
System.out.println(maximum value=”+m);
int m=Math.min(a,b);
System.out.println(“minimum value=”+m);
}}
Q: What is a token? List the different types of tokens supported by java.
Q: 1.Define the following
c. Keywords
d. Literals
2. Define the following
c. Identifiers
d. Separators
The smallest individual unit of the java program is called tokens

Types of tokens in Java


6. Reserved word
7. Identifiers
8. Literals
9. Operators
10. Separators
4. Reserved word or Keywords:
Keywords are an essential part of a java language. These keywords cannot used to name
variable or class .Some of the keywords are
final,static,super,implements,extends,class,int ,try ,catch,throw stc.

Q: Define the term identifier. Give an example.


5. Identifiers identifiers are used for naming variables, classes, methods, objects etc.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

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. Literalsliterals 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.
OperatorsAn 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.

SeparatorsSeparators 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;

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

Note:The destination type is larger than the source type automatic conversion is done
byte b=78;
int a=b;

Standard default Values


In java, every variable has a default value
Type size in bits default value
boolean 1 False
char 16 Null character
byte 8 Zero (byte) 0
short 16 Zero (byte) 0
int 32 Zero 0
long 64 Zero 0 l
float 32 Zero 0
double 64 Zero 0 d
Question Answers
Q: List and explain any 8 java features
Q:List and Explain features of java.
• Compiled and Interpreted
• Usually a computer language is either complied or interpreted. Java combines both
these approaches thus making java 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.
• Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
• Multithreaded − With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.
• High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
• Distributed − Java is designed for the distributed environment of the internet.
• Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of
run-time information that can be used to verify and resolve accesses to objects on
run-tim
• Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
• Platform Independent − Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever platform it is being run
on.
• Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
• Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.

Aparna Nayak L/CS


Dr. TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P

• Portable − Being architecture-neutral and having no implementation dependent


aspects of the specification makes Java portable. Compiler in Java is written in ANSI
C with a clean portability boundary, which is a POSIX subset.
• Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.

Q:List some of the JDK tools


1. Javac—Java compiler, which translates java source code to byte code.
2. Java—Java interpreter, which translates byte code to machine code & then executes.
3. Appletviewer—It is used to run java applets.
4. JDB—Java debugger, which helps us to find errors in our programs.
5. Javah—Java header file generation tool, used while executing “Native Methods”. It
produces both header and source files. 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.

Aparna Nayak L/CS

You might also like