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

Programming in Java Unit 1 2

Uploaded by

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

Programming in Java Unit 1 2

Uploaded by

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

Unit - 1: JAVA Fundamentals

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.

#Program= set of instructions.


#Software= collection of programs (can be a single program as well) + supporting files + Graphics (GUI).
Computer Programmer needs one computer programming language with its IDE, coding skills and compiler
to do computer programming. There are hundreds of programming languages such as C, C++, Java,
QBASIC, Visual Basic, PHP, COBOL, FORTRAN, LISP, etc. and each of them has their own strength and
weakness. One should choose one or two as per the purpose of program, knowledge and skill of a
programmer, simplicity and efficiency of the language.
A programming language can be defined as a set of vocabulary, called ‘keywords’, and a set of rules called
‘Syntax’ to instruct computer to perform certain operations.
Depending on the closeness of the closeness to the machine or human being, languages can be divided into
4 major categories that can be further divided into 5 generations:
a. Low Level Languages/ Machine Languages/ First Generation Languages(1GL)
b. Assembly Level Languages/ Second Generation Languages(2GL)
c. High Level Languages:
i) Procedural Languages/ Third Generation Languages(3GL)
ii) Problem-oriented Languages/ Fourth Generation Languages(4GL)
d. Natural languages/ Fifth Generation Languages(5GL)
a. Low Level Languages or Machine Languages or 1GL:
Digital computers work on binary system. Machine level language is the language developed using series
of binary 1’s and 0’s for statements, text, symbols, numbers or pictures. This is the only language that is
understood by the computer.
b. Assembly Level Languages or 2GL:
Assembly level language is a low-level language designed for a specific type of processor that is same as
machine language but uses mnemonics instead of just numbers. Instead of binary numbers, it uses English
like words or abbreviations such as ADD, SUB, MUL, HLT, etc. called ‘Mnemonics’.
c. High Level languages:
Any languages above assembly language which are independent of type of computer are known as high
level languages. These languages are far from machine language but close to human language. It can be
divided into 2 generations as follows:
i. Procedural Languages or 3GL:
The languages which need step by step instructions in sequence are known as procedural languages, also
called third generation languages. Programmer can write programs using symbols, words and certain rules
like English language.
For eg: C, C++, Java, PHP, Visual Basic, etc.

Programming in Java (XI) - Er. Niroj Kumar Shrestha


ii. Problem-oriented Languages or 4GL:
The languages which are application specific and used to solve specific problems are called problem-
oriented languages.
For e.g.: SQL and PLUS for database, HTML and PHP for WWW, etc.

d. Natural languages or 5GL:


The languages used by human beings to communicate are called natural languages or 5GL. It is used by
fifth generation computers to make natural human like interactions.
For e.g.: English, Nepali, Chinese, etc.
After the clarification that only machine language is understood by computers, every other language except
machine level language must be translated to machine code using specific programs. There are 3 types of
translators that translate assembly language or high-level language into machine code. They are:
a. Compiler: The system program that translates a program written in high level language to machine
language is called compiler.
b. Interpreter: Interpreter is a computer program that directly executes instructions written in a
programming language i.e., source code into byte code, without requiring them previously to have been
complied into a machine language program.
c. Assembler: Assembler is a special program that translate programs written in assembly language rather
than high level language.

1.1 Introduction to Java (also History)


OOP, short for Object Oriented Programming, is a programming paradigm based on the concept of objects
which is the combination of data in the form of fields and code in the form of procedures. Simply saying,
OOP is a way of writing computer programs using the idea of objects to represent data and methods.
Java is a case-sensitive, general-purpose, class-based and independent object-oriented programming
language design for having less implement dependencies. Java was conceived by James Gosling, Patrick
Naughton, Chris Warth, and Mike Sheridan at Sun Microsystem in 1991.
This language was initially called “Oak,” but was renamed “Java” in 1995. Between the initial
implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many
more people contributed to the design and evolution of the language. Somewhat surprisingly, the original
impetus for java was not the Internet! Instead, the primary motivation was the need for a platform-
independent language that could be used to create software to be embedded in various consumer electronics
device, such as microwave ovens and remote controls. The trouble with C and C++ (and most other
language) is that they are designed to be compiled for a specific target. Although it is possible to compile a
C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU.
The problem is that compilers are expensive and time-consuming to create. An easier and more cost-
efficient solution was needed. In an attempt to find such a solution, Gosling and others began work on a
portable, platform-independent language that could be used to produce code that would run on a variety of
CPUs under differing environments. This effort ultimately led to the creation of Java.

Programming in Java (XI) - Er. Niroj Kumar Shrestha


About the time that the details of Java were being worked out, a second, and ultimately more important,
factor was emerging that would play a crucial role in the future of Java. This second force was, of course,
the World Wide Web. Had the web not taken shape at about the same time that Java at the same time that
Java was being implemented, Java might have remained a useful but obscure (doubtful) language for
programming consumer electronics. However, with the emergence of the World Wide Web, Java was
propelled to the forefront of computer language design, because the Web, too, demanded portable programs.
By 1993, it becomes obvious to members of the Java design team that the problems of portability frequently
encountered when creating code for embedded controllers are also found when attempting to create code
for the Internet programming. So, while the desire for an architecture-neutral programming language
provided the initial spark, the Internet ultimately led to Java’s large-scale success.
Because of the similarities between Java and C++, it is tempting to think of Java as simply the “internet
version of C++”. However, to do so would be a large mistake. Java has significant practical and
philosophical difference. While it is true that Java was influence by C++, it is not an enhanced version of
C++. For example, Java is neither upwardly nor downwardly compatible with C++. One other point: Java
was not designed to replace C++. Java was designed to solve a certain set of problems. C++ was designed
to solve a different set of problems. C++ was designed to solve a different set of problems. Both will coexist
for many years to come. It is said that computer language evolves for two reasons: to adapt to changes in
environment and to implement advances in the art of programming. The environmental change that
prompted Java was the need for platform-independent programs destined for distribution on the Internet.
However, Java also embodies changes in the way that people approach the writing of programs. For
example, Java enhanced and refined the object-oriented paradigm used by C++, added integrated support
for multithreading, and provided a library that simplified Internet access. Java was the perfect response to
the demand of the then newly emerging, highly distributed computing universe. Java was Internet
programming what C was to system programming: a revolutionary force that changed the world.
Intermediate language, and byte-code
The programs are first translated into an intermediate language that is the same for all application (or all
computers), and then a small, easy-to-write and hence, inexpensive program translates this intermediate
language into the machine language for a particular appliance or computer. This intermediate language is
called Java bytecode, or simply, byte-code. Since there is only one intermediate language, the hardest step
of the two-step translation from program to intermediate language to machine language is the same for all
appliance (or all computer); hence, most of the cost of translating to multiple machine language was saved.
The language for programming has become a widely used programming language. Today Java is owned by
Oracle Corporation, which purchased Sun Microsystems in 2010.
Why call it byte-code? The word code is commonly used to mean a program or part of program. A byte is
a small unit of storage (eight bits to be precise). Computer readable information is typically organized into
bytes. So the term byte-code suggests a program that is readable by a computer as opposed to a person.

Java Technologies (J2SE, J2EE, J2ME):

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:

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Java Platform, Standard Edition (Java SE):

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 Platform, Enterprise Edition (Java EE):

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 Platform, Micro Edition (Java ME):

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:

1. Javac (Java Compiler):


Javac is the primary Java Compiler included in the Java Development Kit from Oracle Corporation.
The Javac tool reads class and interface definition written in java programming languages and compiles
them into byte code class files. It can also process annotations in Java source files and classes. There
are two ways to pass source file names to Javac. They are:
a. For a small number of source files, simply list the file names on the command line.
b. For a large number of source files, list the filenames in a file separated by blanks or line break
then use the list file name on the javac command line, preceded by an @ character.
2. Java (Java Interpreter):
Java, also known as Java Interpreter, is used to execute bytecode of Java. It takes bytecode as input and
runs it and produces the output. It translates a dot(.)class file created by Javac into code that can be
executed on the underline machine. It takes less amount of time to analyze the source code but the
overall execution time is slower. No any intermediate object code is generated; hence it is memory
efficient. It continues translating the program until the first error is met after which it stops. Hence,
debugging is easy.

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.”);
}
}

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Then, if this program is compiled using javac command as below:
C:\Examples> javac Test.java

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.

/** Javadoc comment…….

*/

Programming in Java (XI) - Er. Niroj Kumar Shrestha


@author @version @description

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:

>java.exe –jar myJava_app.jar

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.

Java Program Java Compiler Virtual Machine

Source code Bytecode


Fig.: Process of Compilation
The virtual machine code is not machine specific. The machine specific code is generated by the Java
interpreter by acting as an intermediary between JVM and the real machine as below:

ByteCode Java Interpreter Machine code

Virtual Machine

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Fig.: Process of converting bytecode into machine code

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 consists of following components:


a. Deployment technologies that include Java plug-in, deployment, etc.
b. Integration libraries that include Java Database Connectivity, Java Naming, etc.
c. Other base libraries including Java Management Extensions, security and Java for XML
processing.
d. Lang and util base libraries including lang and util management, JAR, logging, Reference
Objects and Regular expressions.
e. JVM including Java Hotspot Client and Server Virtual Machines.

JRE plays vital role to execute Java code as java file needs it to run.

JDK
JRE

JVM + Library Classes + Development Tools

JDK = (JVM + Library Classes = JRE) + Development Tools

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.

Programming in Java (XI) - Er. Niroj Kumar Shrestha


9. JDBC:
JDBC, stands for Java DataBase Connectivity, is an application programming interface (API) for the
programming language Java which defines how a client may access as database. It is a Java API to
connect and execute the query with the database. It is a part of Java SE.

Java Application

JDBC API

Drive Manager

JDBC JDBC JDBC


Driver Driver Driver

Oracle MySQL SQL

Fig.: Working Mechanism of JDBC

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.

1.2 Basic structure of Java program:


The basic structure of Java is:

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Simple program in Java:
class FirstClass {
public static void main (String[ ] args) {
System.out.println(“Welcome to Basic concept of Java");
}
}

1.3 Characteristics of Java

The main features and characteristics of Java are as follows:

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.

Example of Class and Object:


public class MyValue {
int x = 5;
public static void main(String[] args) {
MyValue myObj = new MyValue();
System.out.println(myObj.x);
}
}

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.

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Example of Encapsulation:
public class Student{
//data member
private String college="Engineering 11";
//member method
public String getCollege(){
return college;
}
}

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");
}
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}

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

Programming in Java (XI) - Er. Niroj Kumar Shrestha


or a base class or a parent class. The sub class is also known as child class or derived class that have
combined features of parent class and itself.

Syntax of Java Inheritance:


class Subclass-name extends Superclass-name
{
//methods and fields
}

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.

Example of Method Overloading:


class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Output:
Arguments: 1
Arguments: 1 and 4

Example of Method Overriding:


class Animal{
void eat(){
System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){
System.out.println("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}
}

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.

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Unit -2: Data types and Variables
Java Tokens:
A java program is basically a collection of classes and methods. Each methods consists of various
statements and a statement is made up of variables, constants, operators and so on. The smallest element of
a program that are identified by the compiler and separated by delimiters are known as Java Tokens.

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

Fig.: Java Tokens

Java language includes five types of tokens as below:


1. Reserved Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

2.1 Data types


A data type is a classification of data, which can store a specific type of information. Data types are
primarily used in computer programming, in which variables are created to store data. Each variable is
assigned a data type that determines what type of data the variable may contain.
Data type specifies the size and type of values that can be stored in an identifier. The Java language is rich
in its data types. Different data types allow to select the type appropriate to the needs of the application.
It can be divided in two types as:
1. Primitive data type, and
2. Non-primitive data type

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Fig.: Data types in Java

1. Primitive Data type:


Primitive data types are predefined types of data, which are supported by the programming language
and are used for creating variables in program. The eight primitive data types are: byte, short, int, long,
float, double, boolean, and char.
The following tables shows the size of primitive data types:
Range of value that can be stored
Data Type Default Value Default size
Boolean FALSE 1 bit Stores TRUE or FALSE
Char '\u0000' 2 byte ‘u0000’ (or 0) to ‘uffff’ (or 65,535, inclusive)
Byte 0 1 byte −128 to 127
Short 0 2 byte −32768 to 32767
Int 0 4 byte −2,147,483,648 to 2,147,483,647
9,223,372,036,854,775,808 to
Long 0L 8 byte
9,223,372,036,854,755,807
Float 0.0f 4 byte 3.4e−038 to 3.4e+038
Double 0.0d 8 byte 1.7e−308 to 1.7e+038

Example:
class PrimitiveDataTypes {
public static void main (String[ ] args)
{
// declaring character
char a = 'G';

Programming in Java (XI) - Er. Niroj Kumar Shrestha


// Integer data type is generally
// used for numeric values
int i = 89;

// use byte and short


// if memory is a constraint/limit
byte b = 4;

// this will give error as number is


// larger than byte range
// byte b1 = 7888888955;

short s = 56;

// this will give error as number is


// larger than short range
// short s1 = 87878787878;

long l = 87878787878L;

// for float use 'f' as suffix


float f = 4.7333434f;

// by default fraction value


// is double in java
double d = 4.355453532;

boolean bo = true;

System.out.println("char: " + a);


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println(“boolean: ” + bo);
}
}
Output:
char: G
integer: 89
byte: 4
short: 56
long: 87878787878
float: 4.7333436
double: 4.355453532

Programming in Java (XI) - Er. Niroj Kumar Shrestha


boolean: true

2. Non-primitive data type/Reference data type:


The Non-primitive data types or Reference data types will contain a memory address of variable value
because the reference types won’t store the variable value directly in memory. These data type are
created by programmer during the coding process. They are strings, objects, arrays, etc.

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”;

ii. Java Arrays:


Java Arrays are the group of similar variables that can be allocated dynamically. Arrays in Java are
homogeneous data structures implemented in Java as objects. Arrays store one or more values of a
specific data type and provide indexed access to store the same. A specific element in an array is
accessed by its index.

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

Example of Non-primitive data types:


interface Animal {
public void eat();
public void travel();
}
public class Job implements Animal {
public static void main(String[ ] args){
String myJob = "Animal CareTaker";
System.out.println(myJob);
public void eat(){
System.out.println ("Tiger eats meat.");
}
public void travel(){
System.out.println ("Tiger roams and travel around his cave.");
}
}
}

Programming in Java (XI) - Er. Niroj Kumar Shrestha


Output:
Animal CareTaker
Tiger eats meat.
Tiger roams and travel around his cave.

Difference between primitive and non-primitive data types are as follows:


1. Primitive types are predefined in Java. Non-primitive types are created by the programmer and is not
defined by Java.
2. Non Primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
3. A primitive type always has a value, whereas non-primitive types can be null.
4. A primitive type starts with a lowercase letter, while non-primitive types start with an uppercase letter.
5. The size of a primitive type depends on the data type, while non-primitive types have all the same size.

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.

2.3 Variables and Constant


Variables:
A variable is a container which holds the value while the java program is executed. A variable is assigned
with a datatype. Variable is a name of memory location. It is a combination of "vary + able" that means
its value can be changed.
A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents
in the program.
Some examples of variable names are: area, length, totalHeight, average, library, etc.

Syntax for variable declaration:


datatype1 variable1, datatype2 variable2, … datatype n variable n;

In Java, there are different types of variables, for example:


 String variables: stores text, such as "Hello". String values are surrounded by double quotes
 int variables : stores integers (whole numbers), without decimals, such as 123 or -123
 float variables : stores floating point numbers, with decimals, such as 19.99 or -19.99
 char variables : stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
 Boolean variables: stores values with two states: true or false

Programming in Java (XI) - Er. Niroj Kumar Shrestha


In general, there are three types of variables in Java:
1. Local Variable:
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2. Instance Variable:
A variable declared inside the class but outside the body of the method, is called instance variable. It is not
declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3. Static Variable:
Static variables also known as class variables are declared with the static keyword in a class, but outside a
method, constructor or a block. A variable which is declared as static is called static variable. It cannot be
local. A single copy of static variable can be created and shared among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the memory.

Example to demonstrate the types of java variables:


class A {
int data=50; //instance variable
static int m=100; //static variable
void method( ){
int n=90; //local variable
}
}//end of class

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

Programming in Java (XI) - Er. Niroj Kumar Shrestha


goto import protected if int new
public package interface default break float

2.5 Access modifiers


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier
on it.
There are four types of Java access modifiers:

Access within within outside package by outside package


Modifier class package subclass only

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");}

Programming in Java (XI) - Er. Niroj Kumar Shrestha


}

//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;

Programming in Java (XI) - Er. Niroj Kumar Shrestha


import pack.*;

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.

2.6 Escape sequences


A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler.
The following table shows the Java escape sequences.

Escape Sequence Description

\t Inserts a tab in the text at this point.

\b Inserts a backspace in the text at this point.

\n Inserts a newline in the text at this point.

\r Inserts a carriage return in the text at this point.

\f Inserts a form feed in the text at this point.

\' Inserts a single quote character in the text at this point.

\" Inserts a double quote character in the text at this point.

\ Inserts a backslash character in the text at this point.

Example:
public class EscapeCharaterExample
{
public static void main(String args[])
{
//it inserts a Tab Space
String str = "Ram\tKhadka";

Programming in Java (XI) - Er. Niroj Kumar Shrestha


System.out.println(str);

//it inserts a New Line


String str1 = "the best way\nto communicate";
System.out.println(str1);

//it insert a backslash


String str2 = "And\\Or";
System.out.println(str2);

//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");

//it insert a Carriage


String str3 = "Carriage\rReturn";
System.out.println(str3);

//it prints a single quote


String str4 = "Wall Street\'s";
System.out.println(str4);

//it prints double quote


String str5 = "\"Engi 11"";
System.out.println(str5);
}
}

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

Programming in Java (XI) - Er. Niroj Kumar Shrestha


1. Single-line Comments:
Single-line comments start with two forward slashes (//). Any text between // and the end of the line is
ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:


// This is a comment
System.out.println("Hello World");
This example uses a single-line comment at the end of a line of code:
System.out.println("Hello World"); // This is a comment
2. Multi-line Comments:
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.

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.

Example of Arithmetic Operator:


class Main {
public static void main(String[] args) {

// declare variables
int a = 12, b = 5;

// addition operator

Programming in Java (XI) - Er. Niroj Kumar Shrestha


System.out.println("a + b = " + (a + b));

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

Example of Relational operator:


class Main {
public static void main(String[] args) {

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

Programming in Java (XI) - Er. Niroj Kumar Shrestha


System.out.println(a != b); // true

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

Example of Logical Operators:


class Main {
public static void main(String[] args) {

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

Example of Assignment Operator:


class Main {
public static void main(String[] args) {

// create variables

Programming in Java (XI) - Er. Niroj Kumar Shrestha


int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}

Output:
var using =: 4
var using +=: 8
var using *=: 32

e. Increment and Decrement Operator:


The ++ and - - are increment and decrement operators respectively. The operator ++ adds one to the
operands while - - subtracts one from the operands. Eg.: x++ (x=x+1), x- - (x=x-1), etc.

Example of Increment and Decrement Operators:


class Main {
public static void main(String[] args) {

// 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);

System.out.println("Value of b: " + b);

// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);

Programming in Java (XI) - Er. Niroj Kumar Shrestha


}
}

Output:
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11

f. Conditional/ Ternary Operator:


The character pair ? : is a ternary operator available in Java. This operator is used to construct conditional
expressions of the form: condition? exp1: exp2;
In this, condition is checked and if valued is non-zero i.e. true, exp1 is evaluated otherwise exp2 is
evaluated. Eg.: x= (a>b)? a:b;

Example of Conditional/ Ternary Operator:


class Java {
public static void main(String[] args) {

int februaryDays = 29;


String result;

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

Example of Bitwise Operators:


public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40 (left shift)
System.out.println(10<<3);//10*2^3=10*8=80 (left shift)

Programming in Java (XI) - Er. Niroj Kumar Shrestha


System.out.println(10>>2);//10/2^2=10/4=2} (right shif)
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}

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) {

String str = "Programiz";


boolean result;

// checks if str is an instanceof


// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}

Output:
Is str an object of String? true

Programming in Java (XI) - Er. Niroj Kumar Shrestha

You might also like