Professional Documents
Culture Documents
(18CS45)
Module-II
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.):
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
7
Syntax for Array of object
class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;
method1();
method2();
----------
methodN();
};
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.
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++
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++
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.
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
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.
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:
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.
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
52
Simple Java Program
class Message
{
//This is a main method. parameter args passed to the
main method
53
class keyword is used to declare a class in java.
54
void is the return type of the method, it means it doesn't return
any value.
main represents startup of the program.
55
JAVA Environment
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.
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.
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.
62
javap: the class file disassembler which helps in converting
byte code files into program description.
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“.
• 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.
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.
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.
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
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
(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 :
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';
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.
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:
82
Initializing a variable: A variable can be initialize in two ways.
They are
(a) Initializing by Assignment statements.
(b) Initializing by Read statements.
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
&& 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) {
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) {
93
4.Ternary Operators
94
class ConditionalOperator {
public static void main(String[] args) {
95
5.Assignment Operator
6.Increment and decrement operator
96
7.Bitwise Operator:
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
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 (<<)
10
Bitwise right Shift Operators(>>)
public class RightShiftOperator {
Output:
10
Unsigned right Shift Operators(>>>)
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
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:
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.
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.
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.
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];
}
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.
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.
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
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:
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
12
(i)Break:
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;
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;
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;
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;
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:
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
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
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;
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