You are on page 1of 150

Object Oriented Concepts

(18CS45)

Module-II

Dr. Sanchari Saha


AP, Dept of CSE,
CMRIT, Bengaluru

1
Course Objective:
This course (18CS45) will enable students to:
Learn fundamental features of object-oriented language and JAVA
Set up Java JDK environment to create, debug and run simple Java programs.
Create multi-threaded programs and event handling mechanisms.
Introduce event driven Graphical User Interface (GUI) programming using applets and
swings.

Course Outcome:
The student will be able to :
Explain the object-oriented concepts and JAVA.
Develop computer programs to solve real world problems in Java.
Develop simple GUI interfaces for a computer program to interact with users, and to
understand the event-based GUI handling principles using swings
CO-PO and CO-PSO Mapping

P P P P P P P
P P P P P P P P
Modules PO O O O S S S S
Course Outcomes Blooms Level O O O O O O O O
covered 5 1 1 1 O O O O
1 2 3 4 6 7 8 9
0 1 2 1 2 3 4

Explain Object-Oriented
CO1 Concepts in C++ and L2 1,2 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
JAVA.
Develop computer
programs for solution of
CO2 L2 2,3 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
real world problems in
Java.
Develop simple GUI
CO3 interfaces for L3 4,5 2 3 3 2 2 2 - - 2 2 - 2 2 - 2 -
interaction with users
Develop Graphical User
CO4 Interface (GUI) with use L3 5 2 3 3 3 2 2 - - 2 2 - 2 2 - 2 -
of Applets and Swings.
Text Book & Reference Book

Textbooks:
1. Sourav Sahay, Object Oriented Programming with C++ , 2nd Ed, Oxford University
Press,2006
2. Herbert Schildt, Java The Complete Reference, 7th Edition, Tata McGraw Hill, 2007.
Reference Books:
1. Mahesh Bhave and Sunil Patekar, "Programming with Java", First Edition, Pearson
Education,2008, ISBN:9788131720806
2. Herbert Schildt, The Complete Reference C++, 4th Edition, Tata McGraw Hill, 2003.
3. Stanley B.Lippmann, Josee Lajore, C++ Primer, 4th Edition, Pearson Education, 2005.
4. Rajkumar Buyya,S Thamarasi selvi, xingchen chu, Object oriented Programming with java,
Tata McGraw Hill education private limited.
5. Richard A Johnson, Introduction to Java Programming and OOAD, CENGAGE Learning.
6. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies
Syllabus
➢Chapter 1: Class and Objects (cont.):

▪ Objects and arrays


▪ Namespaces
▪ Nested classes
▪ Constructors
▪ Destructors

5
Syllabus
➢Chapter 2: Introduction to Java
• Java’s magic: the Byte code
• Java Development Kit (JDK)
• the Java Buzzwords
• Object-oriented programming
• Simple Java programs.
• Data types, variables
• Arrays
• Operators
• Control Statements ( Decision Making, Looping statements)
• Type Casting

6
Chapter 1:
Objects and Arrays: Arrays of Objects

It is possible to have arrays of objects.

The syntax for declaring and using an object array is


exactly the same as it is for any other type of array.

A array variable of type class is called as an array of


objects.

7
Syntax for Array of object
class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;

method1();
method2();
----------
methodN();
};

class-name obj[ size ];

8
// Driver code
int main()
// Defining the function outside {
// the class // This is an array of objects having
#include<iostream> void Employee::getdata() // maximum limit of 30 Employees
using namespace std; { Employee emp[30];
cout << "Enter Id : "; int n, i;
class Employee cin >> id; cout << "Enter Number of
{ cout << "Enter Name : "; Employees - ";
int id; cin >> name; cin >> n;
char name[30]; }
public: // Accessing the function
// Defining the function outside for(i = 0; i < n; i++)
// Declaration of function // the class emp[i].getdata();
void getdata(); void Employee::putdata()
{ cout << "Employee Data - " << endl;
// Declaration of function cout << id << " ";
void putdata(); cout << name << " "; // Accessing the function
}; cout << endl; for(i = 0; i < n; i++)
} emp[i].putdata();
}

9
Objects and Arrays: Arrays inside Class/ Object
Arrays can be declared as the members of a class.
The arrays can be declared as private, public or protected
members of the class.
#include<iostream>
const int size=5;
class student
{
Program to demonstrate
int roll_no;
the concept of arrays as
class members int marks[size];
public:
void getdata ();
void tot_marks ();
};

10
void student :: getdata () void student :: tot_marks()
{ //calculating total marks
cout<<"\nEnter roll no: "; {
Cin>>roll_no; int total=0;
for(int i=0; i<size; i++) for(int i=0; i<size; i++)
{ total = total+marks[i];
cout<<"Enter marks in cout<<"\n\nTotal marks
subject"<<(i+1)<<": "; "<<total;
cin>>marks[i] ; }
}
Output: void main()
student stu;
Enter roll no: 101
Enter marks in subject 1: 67 stu.getdata() ;
Enter marks in subject 2 : 54 stu.tot_marks() ;
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
}
Enter marks in subject 5 : 82
Total marks = 343

11
Namespace in C++

Using namespace, you can define the context in which names are
defined. In essence, a namespace defines a scope.

Namespaces allow us to group named entities that otherwise would


have global scope. This allows organizing the elements of programs
into different logical scopes referred to by names.

Namespace is a feature added in C++ and not present in C.


A namespace is a declarative region that provides a scope to the
identifiers (names of the types, function, variables etc) inside it.

12
Consider a situation, when we have two persons with the same name,
Piyush, in the same class. Whenever we need to differentiate them
definitely we would have to use some additional information along with
their name, like either the usn, or area if they live in a different area or
their mother’s or father’s name, etc.
The same situation can arise in your C++ applications. For example,
you might be writing some code that has a function called xyz() and
there is another library available which is also having same function
xyz(). Now the compiler has no way of knowing which version of xyz()
function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as
additional information to differentiate similar functions, classes, variables
etc. with the same name available in different libraries. Using namespace,
you can define the context in which names are defined. In essence, a
namespace defines a scope.

13
“using namespace std” means we use the namespace named
std. std is an abbreviation for standard. So that means we use
all the things within std namespace. If we don’t want to use this
line of code, we can use the things in this namespace like this.
std::cout, std::endl.

If this namespace is not used, then computer will search for the
cout, cin and endl etc.. When Computer cannot identify those , it
throws errors.

14
The using namespace statement just means that in the scope it is
present, make all the things under the std namespace available
without having to prefix std:: before each of them.

While this practice is okay for short example code or trivial programs,
pulling in the entire std namespace into the global namespace is not
a good habit as it defeats the purpose of namespaces and can lead
to name collisions. This situation is commonly referred to as
namespace pollution.

15
why namespace is used, when we have all in the iostream header
file?
iostream is a file that has all the things like cout, endl and etc is
defined. If we need to use them we need to add that file. So basically
#include <iostream> means copying and pasting the code in that file
to your code. But if we try to use cout, endl in our code without
specifying the namespace it will throw an error, because these are
defined in the std namespace in the iostream.h file like following.
Following is dummy of iostream.h file. This will give you an idea about
how this is defined.

16
So when we run a program to print something, “using namespace std”
says if you find something that is not declared in the current scope go
and check std.
So now you have the answer why both statements
#include <iostream>
using namespace std;

are used. It is because computer needs to know the code for the cout,
cin functionalities and it needs to know which namespace they are
defined.
So as a summary, why you need both the header file and the namespace to run a
simple c++ program, because computer needs to know the definition of the code of the
functionalities. It is defined in the header file. So header file needs to be included.
namespace is needed because if a functionality like cout is used, but not defined in the
current scope computer needs to know where to check. so namespace needs to be
included. Because we are writing the code outside the std namespace.

17
A namespace definition begins with the keyword namespace followed
by the namespace name as follows:

18
19
20
Nested Classes in C++
A nested class is a class which is declared in another enclosing class. A nested class is
a member and as such has the same access rights as any other member. The members
of an enclosing class have no special access to members of a nested class; the usual
access rules shall be obeyed.

21
#include <iostream>
using namespace std; Example
class Nest Program
{
public:
class Display
{ void main()
{
private: int s; Nest::Display x; // creating object of inner
class Display
public:
void sum( int a, int b) // x is a object, objects are accessed
{ using "Nest::Display".
s =a+b;
} x.sum(12, 10);
void show( )
{ x.show();
cout << "\nSum of a and b is:: " << }
s;
}
}; //closing of inner class
}; //closing of outer class

22
23
24
25
26
27
Constructors
Constructors are special class functions which performs initialization of
every object. The Compiler calls the Constructor whenever an object is
created. Constructor’s initialize values to data members after storage
is allocated to the object.
• While defining a constructor you must
class A remember that the name of
{ constructor will be same as the name
int x; of the class, and constructors never
public: A(); //Constructor have return type.
};
• Constructors can be defined either
inside the class definition or outside
class definition using class name and
scope resolution :: operator.
28
Difference between constructor and
member function
• Constructor name must be the same
as class name but functions cannot
have the same name as the class
name.
• Constructors do not have a return type
whereas functions must have a return
type.
• Constructors are automatically called
when an object is created.
• A member function can be virtual, but
there is no concept of virtual
constructors.
• Constructors are invoked at the time of
object creation automatically and
cannot be called explicitly using class
objects.

29
class A
{
int i;
Types of Constructors
public: Constructors are of three types :
A(); //Constructor declared 1. Default Constructor
2. Parametrized Constructor
}; 3. Copy Constructor
A::A() // Constructor definition
{
i=1;
}

30
Default Constructor in C++

The default constructor is the constructor which doesn’t take any


argument. It has no parameters.
In this case, as soon as the object is created the constructor is
called which initializes its data members.
A default constructor is so important for the initialization of object
members, that even if we do not define a constructor explicitly, the
compiler will provide a default constructor implicitly

Syntax :
class_name ()
{
Constructor Definition
}

31
Sample Code
int main()
#include<iostream>
using namespace std; {
construct c;
class construct { int sum = c.a + c.b;
public:
int a, b; cout << "a : " << c.a << endl;
cout << "b : " << c.b << endl;
// Default Constructor cout << "sum : " << sum <<
construct() endl;
{
a = 10;
b = 20; return 0;
} }
};

32
Parameterized Constructor in C++

• Arguments can be passed to the parameterised constructors.


• These arguments help initialize an object when it is created.
• To create a parameterized constructor, simply add
parameters to it the way you would to any other function.
• When you define the constructor’s body, use the parameters
to initialize the object.
• We can also have more than one constructor in a class and
that concept is called constructor overloading.
Uses of Parameterized constructor:
• It is used to initialize the various data elements of different
objects with different values when they are created.
• It is used to overload constructors.

33
Sample Code
#include<iostream>
using namespace std;
class A {
private: int main()
int a, b; {
public: A obj1(10, 15);
A(int a1, int b1)
{ cout << "a = " << obj1.getA() ;
a = a1; cout << ", b = " << obj1.getB();
b = b1;
} return 0;
int getA() }
{
return a;
}
int getB()
{
return b;
} };
34
copy constructor
• A copy constructor is a member function which initializes an
object using another object of the same class.
• Whenever we define one or more non-default constructors( with
parameters ) for a class, a default constructor( without
parameters ) should also be explicitly defined as the compiler will
not provide a default constructor in this case.
• An object can be initialized with another object of same type.
This is same as copying the contents of a class to another class.
• Copy Constructor is a type of constructor which is used to create
a copy of an already existing object of a class type.
• It is usually of the form X (X&), where X is the class name.

35
void Display()
Example : {
cout<<"\nValues :"<< copy_a <<"\t"<< copy_b;
#include<iostream> }
using namespace std; };
class copycon int main()
{ {
int copy_a,copy_b; copycon obj(10,20);
public: copycon obj2=obj; //Copy Constructor
copycon(int x, int y) cout<<"\nI am parameterized Constructor";
{ obj.Display();
//Constructor with Argument // Constructor invoked.
copy_a=x; cout<<"\nI am copy Constructor";
copy_b=y; // Assign Values In obj2.Display();
return 0; Output:
Constructor
} }
I am parameterized Constructor
Values:10 20
I am Copy Constructor
Values:10 20

36
Constructor Overloading
Just like other member functions, constructors can also be
overloaded. In fact when you have both default and parameterized
constructors defined in your class you are having Overloaded
Constructors, one with no parameter and other with parameter.

You can have any number of Constructors in a class that differ in


parameter list.
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x; name="None";
}

37
In this case we have defined two
Student(int x, string str)
constructors with different parameters,
{
hence overloading the constructors.
rollno=x ; name=str ;
}
One more important thing, if you define any
};
constructor explicitly, then the compiler will
not provide default constructor and you will
int main()
have to define it yourself.
{
Student A(10);
In this case if we write Student S; in main(),
Student B(11,"Ram");
it will lead to a compile time error, because
}
we haven't defined default constructor, and
compiler will not provide its default
constructor because we have defined other
parameterized constructors.

38
Destructors

39
Destructors
Destructor is a special class function which destroys the object as
soon as the scope of object ends. The destructor is called
automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the
class name is used for the name of destructor, with a tilde ~ sign as
prefix to it.
Destructors will never have any arguments.

class A
{
public:
~A();
};
40
• Destructor is also a special member function like constructor.
Destructor destroys the class objects created by constructor.
• Destructor has the same name as their class name preceded by a
tilde (~) symbol.
• It is not possible to define more than one destructor.
• The destructor is only one way to destroy the object create by
constructor. Hence destructor can-not be overloaded.
• Destructor neither requires any argument nor returns any value.
• It is automatically called when object goes out of scope.
• Destructor release memory space occupied by the objects
created by constructor.

41
Example to see how Constructor and Destructor is called

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{ Output:
cout<<"Constructor Invoked"<<endl; Constructor Invoked
} Destructor Invoked
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main( )
{
Employee e1;
return 0;
}

42
Example to see how Constructor and Destructor is called
#include<iostream>
using namespace std; int main() {
class Demo { Demo obj1(10, 20);
private: Demo obj2(30, 40); Output
int num1, num2; Demo obj3(50, 60); Inside Constructor
public: obj1.display(); Inside Constructor
Demo(int n1, int n2) { obj2.display();
Inside Constructor
cout<<"Inside Constructor"<<endl; obj3.display();
num1=10
num1 = n1;
num2 = n2; return 0; num2=20
} } num1=30
void display() { num2=40
cout<<"num1 = "<< num1 <<endl; num1=50
cout<<"num2 = "<< num2 <<endl; num2=60
} Inside Destructor
~Demo() { Inside Destructor
cout<<"Inside Destructor"; Inside Destructor
}
};

43
Chapter 2: Introduction to Java

Java Buzzwords / Features

44
Object Oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.

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

45
Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program
runs.
There are two types of platforms software-based and hardware-
based. Java provides a software-based platform.
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:
• Runtime Environment
• API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the
compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere

46
Robust
Robust simply means strong. Java is robust because:

It uses strong memory management.


There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

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

47
Architecture-neutral
Java is architecture neutral because there are no implementation dependent
features, for example, the 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. However, it occupies
4 bytes of memory for both 32 and 64-bit architectures in Java.

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun, Java language is a simple programming
language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

48
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI( Remote Method Invocation) and EJB(Enterprise Java Bean) are used for creating
distributed applications. This feature of Java makes us able to access files by calling
the methods from any machine on the internet

Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and
C++. Java supports dynamic compilation and automatic memory management
(garbage collection).

Portable
Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. The compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.

49
Secure
Java is best known for its security. With Java,
we can develop virus-free systems. Java is
secured because:

• No explicit pointer
• Java Programs run inside a virtual machine
sandbox
• Bytecode Verifier: It checks the code
fragments for illegal code that can violate
access right to objects.
• Security Manager: It determines what
resources a class can access such as
reading and writing to the local disk.

50
Interpreted
Java byte code is translated on the fly to native machine instructions
and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight
process.

High Performance
Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code. It is still a
little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages,
e.g., C, C++, etc.

51
Java Program structure

Java program structure contains six stages. They are:


(1)Documentation section: The documentation section contains a set of
comment lines describing about the program.
(2)Package statement: The first statement allowed in a Java file is a package
statement. This statement declares a package name and informs the compiler
that the class defined here belong to the package.
Package student;
(3)Import statements: Import statements instruct the compiler to load the
specific class that belongs to the mentioned package. Import student.test;
(4)Interface statements: An interface is like a class but includes a group of
method deceleration. This is an optional statement.
(5)Class definition: A Java program may contain multiple class definition The
class are used to map the real world object.
(6)Main method class: The main method creates objects of various classes
and establish communication between them. On reaching to the end of main
the program terminates and the control goes back to operating system.

52
Simple Java Program
class Message
{
//This is a main method. parameter args passed to the
main method

public static void main(String [] args)


{
System.out.println("Welcome to Java World! ");
}
}

53
class keyword is used to declare a class in java.

public keyword is an access modifier which represents visibility,


it means it is visible to all.

static is a keyword, if we declare any method as static, it is


known as static method. The core advantage of static method is
that there is no need to create object to invoke the static method.

The main method is executed by the JVM, so it doesn't require


to create object to invoke the main method. So it saves memory.

54
void is the return type of the method, it means it doesn't return
any value.
main represents startup of the program.

String[] args is used for command line argument. args is an


array which receives the command line argument when the
program runs

System.out.println() is used print statement. System is a


Predefined Class in Java . out is the Output Stream which is
related to console

55
JAVA Environment

Java is one of the most popular and widely used programming


language and platform. A platform is an environment that helps to
develop and run programs written in any programming language.

Java is fast, reliable and secure. From desktop to web applications,


scientific supercomputers to gaming consoles, cell phones to the
Internet, Java is used in every nook and corner.

Java Environment: The programming environment of Java consists of


three components mainly:
• JDK
• JRE
• JVM

56
JAVA VIRTUAL MACHINE
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. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from each
other. However, Java is platform independent. There are three notions of the JVM:
specification, implementation, and instance.

The JVM performs the following main tasks:

Loads code
Verifies code
Executes code
Provides runtime environment

57
JAVA RUNTIME ENVIRONMENT
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 is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files
that JVM uses at runtime.

58
JAVA DEVELOPMENT KIT
JDK is an acronym for Java Development Kit. The Java Development Kit
(JDK) is a software development environment which is used to develop Java
applications and applets. It physically exists. It contains JRE + development
tools.

JDK is an implementation of any one of the below given Java Platforms


released by Oracle Corporation:

Standard Edition Java Platform


Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), etc. to complete the development
of a Java Application.

59
60
Basic JDK Tools:
These tools are the foundation of the Java Development Kit.

javac :
javac is the compiler for the Java programming language; it's used to compile
.java file. It creates a class file which can be run by using java command.
Ex:
c:javac TestFile.java

java:
The loader for Java applications. This tool is an interpreter and can interpret the class
files generated by the javac compiler. When a class file has been created, the java
command can be used to run the Java program.
Ex:
c:java TestFile.class

61
JavaDoc :
JavaDoc is an API documentation generator for the Java language, which
generates documentation in HTML format from Java source code.

appletviewer :
appletviewer run and debug applets without a web browser, its standalone
command-line program to run Java applets.

javah: it produces header files to write native methods.

62
javap: the class file disassembler which helps in converting
byte code files into program description.

jdb: the debugger.

jinfo: This utility gets configuration information from a


running Java process or crash dump.

JConsole: Java Monitoring and Management Console.

63
interactions between JDK and JRE

64
Consider a java source file saved as ‘Example.java’. The file is compiled
into a set of Byte Code that is stored in a “.class” file. Here it will be
“Example.class“.

The following actions occur at runtime as listed below:

• Class Loader
• Byte Code Verifier
• Interpreter
• Execute the Byte Code
• Make appropriate calls to the underlying hardware

65
JVM becomes an instance of JRE at the runtime of a Java program. It is
widely known as a runtime interpreter. JVM largely helps in the
abstraction of inner implementation from the programmers who make use
of libraries for their programs from JDK.

It is mainly responsible for three activities.


• Loading
• Linking
• Initialization

66
JVM(Java Virtual Machine) acts as a run-time engine to run Java
applications. JVM is the one that actually calls the main method present
in a java code.

JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere).

This means a programmer can develop Java code on one system and
can expect it to run on any other Java-enabled system without any
adjustments. This is all possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the
same class names present in .java file are generated by the Java
compiler. This .class file goes into various steps when we run it. These
steps together describe the whole JVM.

67
Java Byte code
Java bytecode is the instruction set for the Java Virtual Machine. It
acts similar to an assembler which is an alias representation of a C++
code. As soon as a java program is compiled, java bytecode is
generated. In more apt terms, java bytecode is the machine code in
the form of a .class file. With the help of java bytecode, we
achieve platform independence in java.

When we write a program in Java, firstly, the compiler compiles that


program and a bytecode is generated for that piece of code. When we
wish to run this .class file on any other platform, we can do so. After the
first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration.

68
This essentially means that
we only need to have basic
java installation on any
platforms that we want to
run our code on. Resources
required to run the bytecode
are made available by the
Java Virtual Machine, which
calls the processor to
allocate the required
resources. JVM's are stack-
based so they stack
implementation to read the
codes.

69
When a Java program is executed, the compiler compiles that piece
of code and a Bytecode is generated for each method in that program
in the form of a .class file.
We can run this bytecode on any other platform as well. But the
bytecode is a non-runnable code that requires or relies on an
interpreter. This is where JVM plays an important part.
The bytecode generated after the compilation is run by the Java
virtual machine. Resources required for the execution are made
available by the Java virtual machine for smooth execution which
calls the processor to allocate the resources.
Bytecode vs Machine code
• The main difference between the machine code and the bytecode is that the
machine code is a set of instructions in machine language or binary which can be
directly executed by the CPU.
• While the bytecode is a non-runnable code generated by compiling a source code
that relies on an interpreter to get executed.

70
Advantages of Bytecode

Following are a few advantages of Bytecode:


•It helps in achieving platform-independence
•The set of instructions for a JVM may differ from system to system but can
all interpret Bytecode.
•Bytecodes are non-runnable codes that rely on the availability of an
interpreter, this is where JVM comes into play.
•It is a machine-level language code that runs on the JVM.
•It adds portability to Java which resonates with the saying, “write once,
read anywhere”.

71
Steps involved to execute a Java program
Java program execution follows 5 majors steps:
Edit - Here the programmer uses a simple editor or a notepad application to write the
java program and in the end give it a ".java" extension.
Compile - In this step, the programmer gives the javac command and the .java files are
converted into bytecode which is the language understood by the Java virtual machine
(and this is what makes Java platform independent language). Any compile time errors
are raised at this step.
Load - The program is then loaded into memory. This is done by the class loader which
takes the .class files containing the bytecode and stores it in the memory. The .class file
can be loaded from your hard disk or from the network as well.
Verify - The bytecode verifier checks if the bytecode loaded are valid and do not breach
java security restrictions.
Execute - The JVM interprets the program one bytecode at a time and runs the
program.

72
Compilation and Execution of a Java Program

Java, being a platform independent programming language,


doesn’t work on one-step-compilation. Instead, it involves a two-
step execution, first through an OS independent compiler; and
second, in a virtual machine (JVM) which is custom-built for every
operating system. The two principle stages are explained below:

(1) Compilation
First, the source ‘.java’ file is passed through the compiler, which then
encodes the source code into a machine independent encoding, known as
Bytecode. The content of each class contained in the source file is stored
in a separate ‘.class’ file.

73
(2) Execution
The class files generated by the compiler are independent of the
machine or the OS, which allows them to be run on any system.
To run, the main class file (the class that contains the method
main) is passed to the JVM, and then goes through three main
stages before the final machine code is executed. These stages
are:

Class Loader
The main class is loaded into the memory by passing its ‘.class’
file to the JVM, through invoking the latter. All the other classes
referenced in the program are loaded through the class loader

74
Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected
by the bytecode verifier, whose job is to check that the instructions don’t perform
damaging actions. The following are some of the checks carried out:
• Variables are initialized before they are used.
• Method calls match the types of object references.
• Rules for accessing private data and methods are not violated.
• Local variable accesses fall within the runtime stack.
• The run time stack does not overflow.
• If any of the above checks fails, the verifier doesn’t allow the class to be
loaded.
Just-In-Time Compiler
• This is the final stage encountered by the java program, and its job is
to convert the loaded bytecode into machine code. When using a JIT compiler,
the hardware can execute the native code, as opposed to having the JVM
interpret the same sequence of bytecode repeatedly and incurring the penalty
of a relatively lengthy translation process.

75
Due to the two-
step execution
process described
above, a java
program is
independent of the
target operating
system.

76
Data Types in Java:
In java, data types are
classified into two categories :

1. Primitive Data type


2. Non-Primitive Data type

Data Type Default Value Default size


boolean False 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

77
class DataTypes{
public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
Example program for long longVar = 60;
float floatVar = 20;
Datatype in Java double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';

System.out.println("Value Of byte Variable is " + byteVar);


System.out.println("Value Of short Variable is " + shortVar);
System.out.println("Value Of int Variable is " + intVar);
System.out.println("Value Of long Variable is " + longVar);
System.out.println("Value Of float Variable is " + floatVar);
System.out.println("Value Of double Variable is " +
doubleVar);
System.out.println("Value Of boolean Variable is " +
booleanVar);
System.out.println("Value Of char Variable is " + charVar);
}
}

78
Java Tokens
Java program is basically a collection of classes. A class is defined by a set
of declaration statements and methods containing executable statements.
Most statement contains an expression that contains the action carried out
on data. The compiler recognizes the tokens for building up the expression
and statements. Smallest individual units of programs are known as tokens.
Java language includes five types of tokens. They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.

79
(1)Reserved keyword: Java language has 60 words as reserved keywords.
They implement specific feature of the language. The keywords combined with
operators and separators according to syntax build the Java language.

(2)Identifiers: Identifiers are programmer-designed token used for naming classes


methods variable, objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.

80
(3) Literals: Literals in Java are sequence of characters that represents constant
values to be stored in variables. Java language specifies five major types of Literals. They
are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
(4) Operators: An operator is a symbol that takes one or more arguments and
operates on them to produce an result.
(5) Separators: Separators are the symbols that indicates where group of code are
divided and arranged. Some of the operators are:
1. Parentheses()
2. Braces{ }
3. Brackets [ ]
4. Semicolon ;
5. Comma ,
6. Period .

81
Variables:
A variable is an identifier that denotes a storage location used to store a
data value. A variable may have different value in the different phase of
the program. To declare one identifier as a variable there are certain
rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.

Declaring Variable:

One variable should be declared before using.


The syntax is Data-type variblaname1,
variablename2,variablenameN;

82
Initializing a variable: A variable can be initialize in two ways.
They are
(a) Initializing by Assignment statements.
(b) Initializing by Read statements.

Initializing by assignment statements:

One variable can be initialize using assignment statements.

The syntax is : Variable-name = Value;

Initialization of this type can be done while declaration.

Initializing by read statements: Using read statements we can get the


values in the variable.
83
Scope of Variable: Java variable is classified into three types. They are

(a) Instance Variable


(b) Local Variable
(c) Class Variable

Instance Variable: Instance variable is created when objects are


instantiated and therefore they are associated with the object. They take
different values for each object.
Class Variable: Class variable is global to the class and belongs to the
entire set of object that class creates. Only one memory location is
created for each class variable.
Local Variable: Variable declared inside the method are known as local
variables. Local variables are also can be declared with in program
blocks. Program blocks can be nested. But the inner blocks cannot have
same variable that the outer blocks are having.
84
Java Operators
Java operators can be categorized into following
ways:

(1) Arithmetic operator


(2) Relational operator
(3) Logical operator
(4) Assignment operator
(5) Increment and decrement operator
(6) Conditional operator
(7) Bitwise operator
(8) Special operator.

85
Java Operator Precedence Table
Larger Precedence number means higher precedence.

86
87
1.Arithmetic Operators

Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

88
Example program for
public class ArithmeticOperatorDemo { arithmetic operator in Java
// Demonstrate the basic arithmetic operators.
public static void main(String args[])
{
// arithmetic using integers
System.out.println("Integer Arithmetic");
int i = 1 + 1;
int n = i * 3; // arithmetic using doubles
System.out.println("\floating Point Arithmetic");
int m = n / 4;
double a = 1 + 1;
int p = m - i; double b = a * 3;
int q = -p; double c = b / 4;
System.out.println("i = " + i); double d = c - a;
double e = -d;
System.out.println("n = " + n); System.out.println("a = " + a);
System.out.println("m = " + m); System.out.println("b = " + b);
System.out.println("p = " + p); System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("q = " + q);
System.out.println("e = " + e);
} }

89
2.Logical Operators

The logical operators || (conditional-OR) and && (conditional-


AND) operate on boolean expressions. Here's how they work.

&& Conditional-AND
|| Conditional-OR

90
A Boolean data type is a value that can only be either true
class LogicalOperator {
or false
public static void main(String[] args) {

int number1 = 1, number2 = 2, number3 = 9;


boolean result;

// At least one expression needs to be true for the result to be true


result = (number1 > number2) || (number3 > number1);

// result will be true because (number1 > number2) is true Output:


System.out.println(result);
true
// All expression must be true from result to be true false
result = (number1 > number2) && (number3 > number1);

// result will be false because (number3 > number1) is false


System.out.println(result);
}
}

91
3.Relational Operators
The equality and relational operators determine the relationship
between the two operands. It checks if an operand is greater
than, less than, equal to, not equal to and so on. Depending on
the relationship, it is evaluated to either true or false.

== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

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

int number1 = 5, number2 = 6;

if (number1 > number2) {


System.out.println("number1 is greater than
number2.");
}
else {
System.out.println("number2 is greater than
number1.");
}
}
}

93
4.Ternary Operators

The conditional operator or ternary operator ?: is shorthand for


the if-then-else statement. The syntax of the conditional operator
is:

variable = Expression ? expression1 : expression2


Here's how it works.

If the Expression is true, expression1 is assigned to the variable.


If the Expression is false, expression2 is assigned to the
variable.

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

int februaryDays = 29;


String result;

result = (februaryDays == 28) ? "Not a leap


year" : "Leap year";
System.out.println(result);
}
}

95
5.Assignment Operator
6.Increment and decrement operator

+= : Plus and assign to


-= : Minus and assign to ++ : Increment by One
*= : Multiply and assign to. {Pre/Post)
/= : Divide and assign to. -- : Decrement by one
%= : Mod and assign to. (pre/post)
= : Simple assign to.

96
7.Bitwise Operator:

Bit wise operator manipulates the data at Bit level. These


operators are used for tasting the bits. The bit wise operators are:

& : Bitwise AND


! : Bitwise OR
^ : Bitwise exclusive OR
~ : One’s Complement.
<< : Shift left.
>> : Shift Right.
>>> : Shift right with zero fill

97
Example:
Bitwise operator works on bits and performs bit-by-bit
operation.
Assume if a = 60; and b = 13; now in binary format they
will be as follows:

a = 0011 1100
b = 0000 1101

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

98
class Bitlogic
{
public static void main(String args[])
{
String binary[] =
{"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"};

int a = 3; int b = 6;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a&b)|(a & ~b);
System.out.println("a or b :"+binary[c]);
System.out.println("a and b : "+binary[d]);
System.out.println("a xor b : "+binary[e]);
System.out.println("(~a&b)|(a & ~b) : "+binary[f]);
}
}

99
<< Binary Left Shift Operator. The left operands A << 2 will give 240
value is moved left by the number of bits specified which is 1111 0000
by the right operand.

>> Binary Right Shift Operator. The left operands A >> 2 will give 15
value is moved right by the number of bits specified which is 1111
by the right operand.

>>> Shift right zero fill Operator. The left operands A >>>2 will give 15
value is moved right by the number of bits specified which is 0000 1111
by the right operand and shifted values are filled up
with zeros.

10
Bitwise left Shift Operators (<<)

Here we are considering a public class LeftShiftOperator {


simple int data type having 2
value to which we want just public static void main(String[] args) {
one left shit. As number 2’s
binary equivalent is 10 (i.e. int a=2;//10
one zero). And if its bits are int i;
simple move just one left i=a<<1;//100
shift then resultant value will System.out.println("the value of a before left shift is: "
be 100 (one zero zero) +a);
whose decimal is 4. And System.out.println("the value of a after applying left
that’s the truth that when shift is: " +i);
input given in program code Output:
available and output result is }
4 which is desired. the value of a before left shift is: 2
} the value of a after applying left shift is:
4

10
Bitwise right Shift Operators(>>)
public class RightShiftOperator {

public static void main(String[] args) {


Bitwise Right Shift int a=2;
int i;
Operator is applied on the i=a>>1;
number of bits. In this System.out.println("the value of a before right
shift is: " +a);
shift operator the Bit System.out.println("the value of a after applying
value for given number is right shift is: " +i);
simply move to right side
and left most bits are }
replaced with the zeros.
}

Output:

the value of a before right shift is: 2


the value of a after applying right shift is: 1

10
Unsigned right Shift Operators(>>>)

The unsigned right-shift operator is a special type of right-shift operator that


doesn't use the sign bit for filling the trailing position. The unsigned right-shift
operator always fills the trialing position by 0.

Let's take the same example of the right-shift operator to understand the
concept of the left-shift operator.

x => 40 => 0000 0000 0000 0000 0000 0000 0010 1000

A negative number is the 2's complement of its positive number. So,

Y => -40 => 1111 1111 1111 1111 1111 1111 1101 1000

Thus x >>> 2 = 0000 0000 0000 0000 0000 0000 0000 1010

AND y >>> 2 = 0011 1111 1111 1111 1111 1111 1111 0110
10
10
8.Special Operator:

• Instanceof operator:

The java instanceof operator is used to test whether the object is an


instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator
because it compares the instance with type. It returns either true or
false.
Example:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
10
If we apply instanceof operator with a variable that have null value,
it returns false.

class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}

10
• Dot operator: The dot(.) operator is used to access the instance
variable or method of class object.

public class Dot


{
void display()
{
float d = 67.54;
System.out.println(d);
}
public static void main(String args[])
{
Dot d = new Dot();
d.display(); // method caling
}
}

10
Arrays in Java
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location.

• In Java all arrays are dynamically allocated.


• Since arrays are objects in Java, we can find their length using member
length. This is different from C/C++ where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method
parameter.
• The size of an array must be specified by an int value and not long or short.

10
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
One-Dimensional Arrays :
The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;

10
class array
{
public static void main (String[] args)
{
// declares an Array of integers & allocating memory for 5 integers.

int[] arr= new int[5];


Output

// initialize the elements of the array Element at index 0 :


10
arr[0] = 10; Element at index 1 :
arr[1] = 20; 20
arr[2] = 30; Element at index 2 :
arr[3] = 40; 30
arr[4] = 50; Element at index 3 :
// accessing the elements of the specified array
40
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
Element at index 4 :
" : "+ arr[i]); 50
} }

11
Another Example (Run time initialization)
package arraysProgram;
import java.util.Scanner;
public class ArrayEx {
public static void main(String[] args)
{ Output:
// Create a scanner of object using System.in.
Enter 5 integer values:
Scanner sc = new Scanner(System.in);
int num[ ] = new int[5]; // Creating an array object. 20
30
System.out.print("Enter " + num.length + " integer values: "); 40
for (int i = 0; i < num.length; i++) 50
num[i] = sc.nextInt(); 60
Sum: 200
// Calculating the sum of input values.
int sum = 0;
for(int i = 0; i< num.length; i++){
sum += num[i];
}

// Displaying sum of input values entered by user.


System.out.println("Sum: " +sum);
}
}
11
Multidimensional arrays are arrays of arrays with each
element of the array holding the reference of other array.
These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of
square brackets ([]) per dimension. Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

11
class multiDimensional Output:
{
public static void main(String args[])
{ 279
// declaring and initializing 2D array 361
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
742
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

11
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.

The syntax of the for-each loop is given below:

for(data_type variable:array) //Java Program to print the array


elements using for-each loop
{
class Testarray1{
//body of the loop public static void main(String args[])
} {
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}

11
Control Statements in Java
A programming language uses control statements to control the
flow of execution of program based on certain conditions. These
are used to cause the flow of execution to advance and branch
based on changes to the state of a program.

Java’s Selection/Decision making statements:


• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return
These statements allow you to control the flow of your program’s
execution based upon conditions known only during run time.

11
2. If- Else statement:
Decision making statements: The general form of if-else statement is
If ( test expression)
{
1. Simple If statement: statement-block1;
}
The general form of single if statement is : else
If ( test expression) {
{ statement-block2;
statement-Block;
} }
statement-Blocks;

11
Java program to illustrate If statement
class IfDemo Java program to illustrate if-else statement
{ class IfElseDemo
public static void main(String args[]) {
{ public static void main(String args[])
int i = 10; {
int i = 10;
if (i > 15)
System.out.println("10 is less than if (i < 15)
15"); System.out.println("i is smaller than 15");
else
// This statement will be executed System.out.println("i is greater than 15");
// as if considers one statement by }
default }
System.out.println("I am Not in if");
}
}

11
3. Cascade if else/ else-if statement

The general form of else-if statement is:


If ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{
statement block3;
}

11
Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

11
4. Nested if – else statement:
The general form of nested if-else statement is:
If ( test condition)
{
if ( test condition)
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}

12
Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement Will only be executed if statement above it is
true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
12
5. Switch statement:

The general form of switch statement is:


Switch ( expression)
{
case value-1:
block-1; break; case Requires a Constant Expression
case value-2:
block-2; break;
......
default:
default block; break;
}

12
Java program to illustrate switch-case
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
} } }

12
Java allows you to use string objects in
the expression of switch statement. In
order to use string, you need to
consider the following points: •It is recommended to use String
values in a switch statement if the data
It must be only string object. you are dealing with is also Strings.
•The expression in the switch cases
must not be null else, a
Object game = "Hockey"; // It is not NullPointerException is thrown (Run-
allowed time).
String game = "Hockey"; // It is OK. •Comparison of Strings in switch
statement is case sensitive. i.e. the
String object is case sensitive. String you have passed and the String
of the case should be equal and,
"Hockey" and "hockey" are not equal. should be in same case (upper or,
lower).
No Null object

12
public class switchExample1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println(“enter game");
String game = sc.next();
switch(game)
{
case "Hockey": case “Cricket” : case Tennis: Output:
System.out.println(“Outdoor game");
break; Let's play Cricket
case "Chess": case “Ludo” : case “carrom”:
System.out.println(“indoor game");
break;

default:
System.out.println(“ didn’t match”);
}
}
}
12
public class switchExample2 {
public static void main(String[] args) {
String game = "Card-Games";
switch(game){
case "Hockey": case"Cricket": case"Football":
System.out.println("This is a outdoor game");
break;
case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball":
System.out.println("This is a indoor game");
break;
default:
System.out.println("What game it is?"); Output:
}
} This is a indoor game
}

12
6. jump: Java supports three jump statement:

• break
• Continue
• Return

These three statements transfer control to other part of the program.

12
(i)Break:

In Java, break is majorly used for:


▪ Terminate a sequence in a switch statement
▪ To exit a loop.
▪ Used as a “civilized” form of goto.

12
Java program to illustrate using break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;

System.out.println("i: " + i);


}
System.out.println("Loop complete.");
}
}

12
Java program to illustrate using break
with goto
class BreakLabelDemo
{ second:
public static void main(String args[]) {
{ third:
boolean t = true; {
// Before break
// label first System.out.println("Before the
first: break statement");
{
// Illegal statement here as // break will take the control out
label second is not of
// introduced yet break second; // second label

13
if (t)
break second;
System.out.println("This won't
execute.");
}
System.out.println("This won't execute.");
}

// First block
System.out.println("This is after second
block.");
} Output:
}
} Before the break.
This is after second
block.

13
(ii)continue:
Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. This is, in
effect, a goto just past the body of the loop, to the loop’s end. The
continue statement performs such an action.

13
Java program to illustrate using continue in an if statement
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even Output:
// skip and continue
if (i%2 == 0) 13579
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}

13
(iii)return:
The return statement is used to explicitly return from a method. That is,
it causes a program control to transfer back to the caller of the method.
Java program to illustrate using return
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
Output:
if (t)
Before the return. return;

// Compiler will bypass every statement after return


System.out.println("This won't execute.");
}
}
13
Unlike C++, Java does not support the goto statement with same format as in
C/C++. It is reserved as a keyword just in case they wanted to add it to a later version.
Instead, it has label. Labels are used to change the flow of the program and jump to a
specific instruction or label based on a condition. The following illustration may help
you to better understand what a label is.
// Java code to illustrate using label and break instead of goto

public class Main {


public static void main(String[] args)
{
// label for outer loop
outer:
for (int i = 0; i < 10; i++) {
Output:
for (int j = 0; j < 10; j++) { value of j = 0
if (j == 1)
break outer;
System.out.println(" value of j = " + j);
}
} // end of outer loop
} // end of main()
} // end of class Main

13
Loops in Java
Looping in programming languages is a feature which facilitates the
execution of a set of instructions/functions repeatedly while some
condition evaluates to true.
Java provides three ways for executing the loops. While all the ways
provide similar basic functionality, they differ in their syntax and
condition checking time.
(i) While Loop: Syntax :
A while loop is a control flow statement that allows
while (boolean condition)
code to be executed repeatedly based on a given
Boolean condition. The while loop can be thought {
of as a repeating if statement. loop statements...
}

13
// Java program to illustrate while loop
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
System.out.println("Value of x:" + x);

// Increment the value of x for


// next iteration
x++;
} } }

13
(ii) for Loop:
for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.

Syntax:
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}

13
// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}

13
(iii) do-while Loop:

do while loop is similar to while loop with only difference that it


checks for condition after executing the statements, and therefore is
an example of Exit Control Loop.

Syntax:
do
{
statements..
}
while (condition);

14
Java program to illustrate do-while loop
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}

14
Write a Java program to sort array elements using bubble sort
/* Prints the array */
import java. util. *;
void printArray(int arr[])
class BubbleSort
{
{
int n = arr.length;
void bubbleSort(int arr[])
for (int i=0; i<n; ++i)
{
System.out.print(arr[i] + " ");
int n = arr.length;
System.out.println();
for (int i = 0; i < n-1; i++)
}
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
// Driver method to test above
{
public static void main(String args[])
// swap temp and arr[i]
{
int temp = arr[j];
BubbleSort ob = new BubbleSort();
arr[j] = arr[j+1];
int arr[] = {64, 34, 25, 12, 22, 11, 90};
arr[j+1] = temp;
ob.bubbleSort(arr);
}
System.out.println("Sorted array");
}
ob.printArray(arr);
}
}

14
Type Casting in Java

When you assign value of one data type to another, the two types
might not be compatible with each other. If the data types are
compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not then they need to
be casted or converted explicitly.
Widening or Automatic Type Conversion

Widening conversion takes place when two data types are


automatically converted. This happens when:

• The two data types are compatible.


• When we assign value of a smaller
data type to a bigger data type.

14
class Test
{
public static void main(String[] args)
{
int i = 100;
// automatic type conversion
long l = i;
// automatic type conversion
float f = l; Output:
System.out.println("Int value "+i); Int value 100
Long value 100
System.out.println("Long value "+l); Float value 100.0
System.out.println("Float value "+f);
}
}

14
Narrowing or Explicit Conversion

If we want to assign a value of larger data type to a smaller data


type we perform explicit type casting or narrowing.
This is useful for incompatible data types where automatic
conversion cannot be done. Here, target-type specifies the
desired type to convert the specified value to.

14
//Java program to illustrate incompatible data type
for explicit type conversion
public class Test Error:
{ 7: error: incompatible types: possible
public static void main(String[] argv) lossy conversion from int to char
{ ch = num;
^
char ch = 'c'; 1 error
int num = 88;
ch = num;
}
}

14
How to do Explicit Conversion?
Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
Output: double d = 100.04;

Double value //explicit type casting


100.04 long l = (long)d;
Long value 100
//explicit type casting
Int value 100
int i = (int)l;
System.out.println("Double value "+d);
System.out.println("Long value "+l); //fractional part lost
System.out.println("Int value "+i); //fractional part lost
}
}

14
QUESTION BANK
Define a student class with following measures
Data members: Roll no, Name, Marks %
Member function: to read the data, to print the data.
Write a C++ program with array of objects concept to read the data of 10 students but print the
data of 5 students.
Briefly explain the usage of namespace in preventing pollution of the global namespace.
Explain the role of constructor in object-oriented programming. How parameterized
constructor is different than default constructor ? Justify with example programs
How Java Development kit helps in developing and running Java Program? Explain the usage of
each tool in JDK
Write a program to define the class student which has two member variables called name and
age. Define the default constructor , member functions get-data ( ) for taking name and age of
student and print-data ( ) for displaying data of student.
With a neat diagram explain Java program execution flow. Explain how bytecode helps Java
programs to achieve portability

14
Write a program with a class called ‘arithmetic’ having two integer and one
character data members. It performs the operation on its integer members
indicated by character member ( +, -, *, /). For example, ‘+’ indicates addition on
data members. Write a class with all the necessary constructors and methods to
perform the operation and print the result of the operation
“Java is a revolutionary programming language”. Justify this statement
Whether ‘compile once and run anywhere’ is possible in java? Justify your
answer with suitable explanation
How is destructor used in a program ? Explain with an example program
In Java why type casting is needed? Illustrate with an example
Write a Java Program to initialize and display integer and floating-point variables.

14
Write a Java Program to print factorial of a number ‘n’ using for loop
In what kind of scenario do-while loop and switch statement is used in Java. Justify your answer
with suitable program
Write a program in Java to perform row element *column element operation
Write a Java program that creates and initializes a 5-integer element array. Calculate and display the
average of its values
Explain the use of left shift and right shift operators in Java with relevant example program. Which
operators in Java are named as short circuit operators? Why the name so? Explain
Write a Java program demonstrating the use of relational operators
Whether operator precedence is important in programming? Justify your answer. Explain the
operation of the following operators with a single example program
(i)++ (ii) - -
Write a Java program to show the usage of various data types present in Java language.

15

You might also like