Programming in Java Unit 1 2
Programming in Java Unit 1 2
Computer programming is the process of designing and building an executable computer program
(software) to accomplish a specific computing result.
In another words, Computer programming is the process that professionals use to write code that instructs
how a computer, application or software program performs.
Computer Programming is a set of instructions to facilitate specific actions.
Java technology is both a programming language and a platform. The Java programming language is a high-
level object-oriented language that has a particular syntax and style. A Java platform is a particular
environment in which Java programming language applications run. There are 3 main platforms in Java
which are as follows:
Java SE, formally known as J2SE, stands for Java platform Standard Edition. It is a mostly used
specification that provides rules and guidelines for developing standalone applications and applets that runs
on Desktop. It also provides rules and guidelines for developing JDK software for compiling and executing
stand-alone applications and applets. JDK software is sufficient for compiling and executing Java SE based
applications.
Java EE, formally known as J2EE, stands for Java platform Enterprise Edition. It is the Java platform for
developing enterprise-oriented applications and servlets, which are server programs that conform to Java
EE’s Servlet API. Java EE is built on top of Java SE.
Java ME, formally known as J2ME, stands for Java platform Micro Edition. It is the Java platform for
developing MIDlets, which are programs that run on mobile information devices, and Xlets, which are
programs that run on embedded devices. It is used where more importance is given on memory management
as there is limited memory resources in mobiles.
Java Tools (javac, java, appletviewer, javadoc, jar, JVM, JRE, JDBC, JDK):
There are many Java tools that ease the entire process of developing, testing and deployment in Java. They
are as follows:
Example:
Consider below program is written in notepad and saved to C:\Examples folder.
public class Test{
public static void main (String[ ] args){
System.out.println(“Hi! Welcome to Test Program.”);
}
}
This command compiles the given java file and generates a .class file (bytecode) as Test.class.
And if we execute the generated bytecode (.class) file using the java command, program runs and output
will be shown as below:
C:\Examples> java Test
Hi! Welcome to Test Program.
3. Applet Viewer:
It is a standalone command line program from Sun Microsystem to run Java applets. Java applet is a
small application written in java programming language that runs in web browser and works at client
side.
Generally, Java applets run by the use of web browser but there is another way to run an applet which
is ‘The Java Appletviewer’. This tool acts as a test bed for Java applets. The appletviewer runs on the
HTML documentation and uses embedded applet tags. The appletviewer command connects to the
documents or resources designated by URL’s. It displays each applet referenced by the document in its
own window.
Example:
import Java.applet.*;
public class Myapplet extends Applet{
String str;
public void init( ){
str=”Applet Viewer’s View.”;
}
}
Command:
C:\AppletLocation> javac Myapplet.java
C:\AppletLocation> appletviewer Myapplet.html
It displays the page in Browser
4. Javadoc:
Javadoc tool is a document generator tool in Java Programming language for generating standard
documentation in HTML format. It generates API (Application Program Interface) documentation. It
analyzes the declaration and documentation in a set of source file describing classes, methods,
constructors and fields.
Before using Javadoc tool, Javadoc comments /**…………………*/ must be included providing
information about classes, methods and constructors, etc.
*/
To create a Javadoc, there is no need to compile the java file. To create the Java documentation API,
we just need to write Javadoc followed by file name as:
For example, if you want to document com.mypackage, whose source files reside in the directory
\user\src\com\mypackage, and if this package relies on a library in \user\lib, then you would use the
following command:
javadoc -sourcepath \user\lib -classpath \user\src com.mypackage
After successful execution of the above command, a number of HTML files will be created. We need
to open the file named ‘index’ to see all the information about classes.
5. JAR or jar:
Jar stands for Java Archive (compiosition of more files along with metadata) which is a file format that
contains bundled java class files along with associated image/sound files, resources and metadata. It
contains all of the various components that make up a self-contained, executable Java application,
deployable Java applet or most commonly a Java library to which any Java Runtime Environment can
link. JAR files are packaged with ZIP file format.
The key benefits of using jar file are:
a. The ability to aggregate hundreds or thousands of different files that make up an application.
b. It is the means to compress all of the contained files greatly reducing the size of the application
and making it easier to move the JAR file over a network and between environments.
c. It helps in lossless data compression as well as decompression, and archiving as well as archive
unpacking.
The syntax to run an executable JAR file named myJava_app.jar using JDK’s java.exe utility is as
follows:
6. JVM:
Java Virtual Machine is a virtual machine that enables a computer to run Java programs as well as
programs written in other languages that are also compiled to Java bytecode.
All language compilers translate source code into machine code for a specific computer. Java compiler
also does the same thing. But what makes Java achieve architecture neutrality is that the Java compiler
produces an intermediate code known as bytecode for a machine that doesn’t exist. This machine is
called JVM and it exists only inside the computer memory.
Virtual Machine
Whatever Java program is run using JRE or JDK goes into JVM and JVM is responsible for
executing the java program line by line hence it is also known as interpreter. JVM’s advantage is that
it allows a program to be written and compiled only once which can be run successfully on different
types of hardware.
7. JRE:
Java Runtime Environment, also may be written as ‘Java RTE’, is a set of software tools that combines
JVM, platform core classes and supporting libraries. JRE is part of JDK.
JRE is an installation package which provides environment to only run the java program onto machine
but not to develop. It is only used by end users who just want to run Java programs.
JRE plays vital role to execute Java code as java file needs it to run.
JDK
JRE
8. JDK:
The Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (java),
a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in
Java development.
Java Application
JDBC API
Drive Manager
JDBC API uses JDBC drivers to connect and execute the query with the database (JDBC driver is a
software component that enables java application to interact with the database.
a. Classes
b. Objects
c. Encapsulation
d. Data Abstraction
e. Inheritance
f. Polymorphism
g. Dynamic binding
a. Classes:
Class represents a real-world entity which acts as a blueprint for all the objects. It describes fields (variables)
as well as behaviors (methods) of objects. It can represent real world entity in the form of program.
b. Objects:
Object is an instant of class that has states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors – wagging the tail, barking, eating, etc. Object determines the flow of program in OOP.
Output:
5
c. Encapsulation:
The wrapping up of data and methods into a single unit called class is known as encapsulation. It provides
a layer of security around manipulated data, protecting it from external interference and misuse. In Java, it
is supported by class and objects.
d. Data Abstraction:
It refers to the act of representing essential features without including the background details or
explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes and
methods. We can take an example of driving a car where we don’t need to know all the detailed features,
parts and functionalities of car to drive it.
Example:
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output:
The pig says: wee wee
Zzz
e. Inheritance:
It is the process by which objects of one class acquires the properties of objects of another class. This
concept provides the idea of reusability. The class from which the sub-class is derived is called a super class
Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
f. Polymorphism:
Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors
in different instances. The behavior depends upon the type of data used in the operation. For e.g.: Consider
the operation of addition: for two numbers, the operation will generate a sum. If the operands are strings,
then the operation would produce a third string by concatenation.
This can be obtained in two ways in Java: Method Overloading and Method Overriding.
Output:
Dog is eating
g. Dynamic binding:
Binding refers to the linking of a procedures called to the code to be executed in a response to the call.
Dynamic binding means that the core associated with a given procedure called is not known until the time
of the call at runtime. It is associated with polymorphism and inheritance.
Reserved Keywords
Eg.: double, class, break, etc
Literals Identifiers
Eg.: 431, 14.5e2, 48.55, etc Eg.: 431, 14.5e2, 48.55, etc
Java
Tokens
Seperators Operators
Eg.: ( ),[ ], { }, etc Eg.: +,-, %, <,>, etc
Example:
class PrimitiveDataTypes {
public static void main (String[ ] args)
{
// declaring character
char a = 'G';
short s = 56;
long l = 87878787878L;
boolean bo = true;
i. Strings:
Strings are defined as an array of characters. The difference between a character array and a string is
the string is terminated with a special character ‘\0’. In Java, a string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
Basic syntax for declaring a string in Java programming language.
String string_variable = “sequence_of_string”;
iii. Classes:
A class in Java is a blueprint which includes all your data. A class contains fields(variables) and
methods to describe the behavior of an object.
iv. Interface:
Like a class, an interface can have methods and variables, but the methods declared in interface are by
default abstract (only method signature, no body).
2.2 Identifiers
Identifiers are programmer designed tokens. They are used for naming classes, methods, objects, variables,
packages and interfaces in a program. Java identifiers follow the following rules:
a. They can have alphabets, digits and the underscore and dollar ($) sign characters.
b. They must not begin with a digit.
c. Uppercase and lowercase letters are distinct.
d. They can be of any length.
Example: MyFirstJavaProgram, myAge, average, area, etc.
Constants:
Constants in Java refer to fixed values that do not change during the execution of a program. Java
supports several types of constants as:
1. Integer Constants : 123, -345, 0b0110101, $100, etc.
2. Real Constants : 0.0034, -0.89, 435.36, 0.65e4, etc.
3. Single Character Constants : Single character enclosed between a pair of single quote marks (‘’) e.g.:
‘13’, ‘X’, ‘;’, ‘’, etc.
4. String Constants : Enclosed between double quotes (“”). “Hello Java”, “?....!”, “5+3”, “X”, “1234”,
etc.
5. Backslash Character Constants: \b (back space), \n (new line), \t (horizontal tab), \’ (single quote), \”
(double quote), \\ (backslash), etc.
2.4 Keywords
Keywords are reserved words which act as key to a code and are pre-defined words by Java. They are an
essential part of a language definition. Java language has reserved 50 words as Keywords:
Some of them are:
abstract long case static byte private
const while class short double boolean
do switch final catch extends throws
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
Example:
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
Example:
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:
Hello
Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
Example:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
Hello
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Example:
public class EscapeCharaterExample
{
public static void main(String args[])
{
//it inserts a Tab Space
String str = "Ram\tKhadka";
//it insert form feed (last character of before line will be the place in next line of text after /f)
System.out.println("This is before\fNow new line");
Output:
Ram Khadka
the best way
to communicate
And\Or
This is before
Now new line
Carriage
Return
Wall Street's
"Engi 11"
2.7 Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.
It can be divided into two types as:
1. Single-line Comments
2. Multi-line Comments
This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
2.8 Operators
Java operator is a symbol that takes one or more arguments and operates on them to produce a result. Java
operators can be classified into a number of related categories as:
a. Arithmetic Operator
b. Relational Operator
c. Logical Operator
d. Assignment Operator
e. Increment and Decrement Operator
f. Conditional Operator
g. Bitwise Operator
h. Special Operator
a. Arithmetic Operator:
They are used to construct mathematical expressions as in algebra. Java provides all the basic arithmetic
operators +, -, *, / and %. Arithmetic operators are used as a-b, a*b, a%b, etc. Here ‘a’ and ‘b’ can be
variables or constants which are called operands.
// declare variables
int a = 12, b = 5;
// addition operator
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output:
a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2
b. Relational Operator:
An expression containing a relational operator is known as relational operator. Example: a<b, x>20, etc.
The relational operators are as below:
a. < is less than
b. <= is less than equal to
c. > is greater than
d. >= is greater than equal to
e. == is equal to
f. != is not equal to
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
c. Logical Operator:
The logical operators are && and || which are used when we want to form compound conditions by
combining two or more relations. Eg.: a>b && x=20, a<b || z>5.5, etc.
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
d. Assignment Operator:
Assignment operators are used to assign the value of an expression to a variable. Eg.: x=x+1, x<=x+1, etc.
// create variables
Output:
var using =: 4
var using +=: 8
var using *=: 32
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
Output:
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output:
Leap year
g. Bitwise Operator:
The operator which manipulates the data at values of bit level i.e. bit by bit is knowns as bitwise operator.
This operator may not be applied to float or double.
Bitwise operators are:
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill.
Output:
40
80
2
5
5
-5
1073741819
h. Special Operator:
Java supports some special operators of interest such as ‘instance of’ operator and member selection
operator (.). Eg.: a person instance of Students is true if person belongs to the class Students, then we
can use as person. age, etc.
Example of Special Operators:
class Main {
public static void main(String[] args) {
Output:
Is str an object of String? true