C++
•Called “C with Classes” initially.
•Combines procedural programming (like C) and object-oriented programming (OOP).
•Used in system programming, games, real-time simulations, embedded systems,
competitive programming.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
} •#include <iostream> → header file for
input/output.
•using namespace std; → allows us to use
cout, cin directly.
•int main() → entry point of the program.
•cout → prints output.
•return 0; → ends the program
successfully.
#include<iostream>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student s1;
s1.name = "Alice";
s1.age = 20;
s1.display();
return 0;
}
Key OOP Features:
1.Encapsulation → Wrapping data & methods in a class.
2.Abstraction → Showing only essential details.
3.Inheritance → Reusing code from parent class.
4.Polymorphism → Same function name, different behaviors.
Why Java?
•It’s easier to learn (clean syntax, no manual memory management).
•It’s cross-platform (runs anywhere with JVM).
•It’s the industry standard for enterprise apps, Android, web development.
We don’t use C++ everywhere because:
•It’s more complex (pointers, manual memory).
•It’s platform-dependent.
•It’s more suited for system-level programming, gaming, and performance-critical
tasks, not general-purpose app development.
•What is Java?
• A high-level, object-oriented, platform-independent programming language.
Features of Java over C++
1.Platform Independent (WORA)
1. Java follows Write Once, Run Anywhere.
2. Code is compiled to bytecode → runs on any machine with JVM.
3. C++ produces machine code → compiled separately for Windows, Linux, Mac.
2.Automatic Memory Management
1. Java has Garbage Collector → frees unused memory automatically.
2. In C++, programmer must handle memory manually with new/delete → risk of memory leaks.
3.Simpler & Safer Syntax
1. No pointers (avoids accidental memory access issues).
2. No multiple inheritance confusion (Java uses interfaces instead).
3. Cleaner and beginner-friendly.
4.Large Standard Library
1. Java provides huge built-in APIs (Collections, Networking, GUI, Database, etc.).
2. C++ STL is powerful but limited compared to Java’s ecosystem.
5.Cross-Platform Development
1. Java is the backbone of Android Apps, Web Apps, Enterprise Software, Cloud tools.
2. C++ is not common in these areas (except gaming & embedded).
6.Security
1. Java runs inside JVM (sandbox environment) → more secure.
2. C++ allows direct memory access (risk of hacking, buffer overflow).
JDK (Java Development Kit)
•A software package that contains all tools needed to develop Java
applications.
1. JRE (to run Java programs)
2. Compiler (javac)
3. Debugger (jdb)
4. Archiver (jar) •JDK
•JRE
JRE (Java Runtime Environment) •JVM
•Provides the environment required to run Java •java
applications. •java
•Includes: •java
• JVM (Java Virtual Machine) •jar →
• Core libraries and other files. •jdb
•jshe
Textbook
1. Java: The Complete Reference, 12th Edition, by Herbert Schildt, November 2021, McGraw-Hill,
ISBN: 9781260463422
Reference Books
1. Programming with Java, 6th Edition, by E Balagurusamy, March 2019, McGraw Hill Education,
Introduction to Java
Programming Language
11
Content
• Java language Syntax
• “Hello World” program example
• Compiling, Running and Debugging Java code
• Inheritance
• Threading
• Synchronization
12
Java programming
Language
• Some buzzwords for Java
– “Write Once, Run Anywhere”
– Simple
– Object oriented
– Distributed
– Multithreaded
– Dynamic
– Architecture neutral
– Portable
– High performance
– Robust
– Secure
13
Java’s Magic: The Bytecode-
Byte code is a highly optimized set of
instructions designed to be executed by the
Java run-time system, which is called the Java
Virtual Machine (JVM).
Bytecode is the intermediate representation of
Java programs just as assembler
Compile Once Run Anywhere 4
Java Development Kit (JDK):
Java Development Kit contains two parts. One part contains the utilities like javac,
debugger, jar which helps in compiling the source code (.java files) into byte code (.class
files) and debug the programs. The other part is the JRE, which contains the utilities like
java which help in running/executing the byte code. If we want to write programs and run
them, then we need the JDK installed.
Java Run-time Environment (JRE):
Java Run-time Environment helps in running the programs. JRE contains the JVM, the
java classes/packages and the run-time libraries. If we do not want to write programs, but
only execute the programs written by others, then JRE alone will be sufficient.
Java Virtual Machine (JVM):
Java Virtual Machine is important part of the JRE, which actually runs the programs
(.class files), it uses the java class libraries and the run-time libraries to execute those
programs.
Every operating system(OS) or platform will have a different JVM.
15
16
Object-Oriented
Programming
• Two Paradigms
– All computer programs consist of two elements: code and
data.
– ABSTRACTION
• An essential element of object-oriented programming is abstraction. Humans manage
complexity through abstraction.
• From the outside, the car is a single object. Once inside, you see that the car consists of several
subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so on.
• Three OO Concepts:
Encapsulation
Inheritance
Polymorphism
17
18
Encapsulation
19
20
Inheritance
21
POLYMORPHISM
22
• Polymorphism, Encapsulation, and Inheritance
Work Together
23
Java Basics
Object - Objects have states and behaviours. Example: A dog has states - colour,
name, breed as well as behaviour such as wagging their tail, barking, eating.
An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the
behaviour/state that the object of its type supports.
Methods - A method is basically behaviour. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.
Instance Variables - Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
24
25
Example: Hello World
Program
• Everything is in a class
• One file, one public class
• In the runnable public class:
– public static void main(String []
args)
26
Java Comments
Single-line comments start with two
forward slashes (//).
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by
Java.
27
Java Identifiers
• Names used for classes, variables, and methods are called
identifiers.
• All identifiers should begin with a letter (A to Z or a to z),
currency character ($) or an underscore (_).
• After the first character, identifiers have any
can combination of characters.
• A key word cannot be used as an identifier.
• Most importantly, identifiers are case sensitive.
• Examples of legal identifiers:
age, $salary, _value, 1_value.
• Examples of illegal identifiers: 123abc, -salary
28
Java Modifiers
• Like other languages, it is possible to modify
classes, methods, etc., by using modifiers.
There are two categories of modifiers:
• Access Modifiers: default, public , protected,
private
• Non-access Modifiers: final, abstract,
strictfp
29
Java Keywords
30
Data Types
Statically typed language
31
32
33
Variables in Java
• Syntax: datatype variable name = value;
Variables naming convention in java
• 1) Variables naming cannot contain white spaces, is invalid
because the variable name has space in
it.
2) Variable name can begin with special characters such as $ and _
3)As per the java coding standards the variable name
should begin with a lower case letter, for example int number; For
lengthy variables names that has more than one words do it like
this: int smallNumber; int bigNumber; (start the second word
with capital
letter).
4) Variable names are case sensitive in Java.
34
Types of Variables in Java
1) Local variable
2) Static (or class) variable
3) Instance variable
Variable Initialization:
• To initialize a variable, you must assign it a valid value.
• int a=2,b=4,c=6;
• float pi=3.14f;
• double do=20.22d;
• char a=’v’;
• long myNum = 15000000000L;
35
Static (or class) Variable
• Static variables are also known as class variable
because they are associated with the class and
common for all the instances of class.
• For example, If I create three objects of a class
and access this static variable, it would be
common for all, the changes made to the variable
using one of the object would reflect when you
access it through other objects.
36
• Instance variable
Each instance(objects) of class has its own copy
of instance variable. Unlike static variable,
instance variables have their own separate copy
of instance variable.
37
Local Variable
• These variables are declared inside method of
the class. Their scope is limited to the method
which means that You can’t change their
values and access them outside of the
method.
38
public class bank
{
static String bankname = "HDFC";
static int bankcode =100;
public static void main(String[] args)
{
bank b1 = new bank();
System.out.println(b1.bankname +"\n"+ b1.bankcode);
bank b2 = new bank();
System.out.println(b2.bankname +"\n"+ b2.bankcode);
bank b3 = new bank();
b3.bankname="ICIC";
System.out.println(b3.bankname +"\n"+ b3.bankcode);
}
39
• Calculate area of triangle.
• Program to find ASCII code of a character
40
41
Java
Literals
42
• 1) Decimal literals: Allowed digits are 0 to 9.
• Example: int x=10;
• 2) Octal literals: Allowed digits are 0 to 7. Literal
value should be prefixed with zero.
• Example: int x=010;
• 3) Hexa Decimal literals:
– The allowed digits are 0 to 9, A to Z.
– For the extra digits we can use both upper case and
lower case characters.
– This is one of very few areas where java is not case
sensitive.
– Literal value should be prefixed with ox(or)oX.
– int x=0x10;
43
• long l=10L;(valid)
• long l=10;
• byte b=127;(valid)
• byte b=130; //C.E:possibl
• float f=123.456f;(valid)
• double d=123.456;(valid)e loss of precision(invalid)
• boolean b=true;
• String s=“BMS";
44
• Character Literals
– char ch='a';(valid)
– char ch=97; (valid)
– char ch=0xFace; (valid)
– char ch='\ubeef';
• Binary Literals :
• 1. Decimal
• 2. Octal
• 3. Hexa decimal
Literal value should be prefixed with Ob or OB .
int x = 0b111;
System.out.println(x); // 7
45
46
Lexical Issues
• Whitespace
• Identifiers
• Literals
• Comments
• Separators () , {} [];.
47
Java Type
Casting
In Java, there are two types of casting:
• Widening Casting (automatically) - converting a smaller type to a larger type
size byte -> short -> char -> int -> long -> float -> double
• Narrowing Casting (manually) - converting a larger type to a smaller size
type double -> float -> long -> int -> char -> short -> byte
Type conversion from int to String
String data = String.valueOf(num);
Type conversion from String to Int
int num = Integer.parseInt(data);
48
Type
Conversions
49
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d
= .1234;
double result = (f *
b) + (i / c) - (d * s); 50
class CastingDemo1
{
public static void main(String[] args)
{
double d = 120.04;
long l = (long)d;
int i = (int)l;
System.out.println
("Double value
"+d);
System.out.println
("Long value "+l);
System.out.println
("Int value "+i);
}
51
byte b;
int i = 355;
b = (byte) i;
52
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads an int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
char c = sc.next().charAt(0);
next() function returns the next token/word in the input as a string and
charAt(0) function returns the first character in that string. 43
int n = 1;
Declaring Variables [3]
char ch = ‘A’;
String s =
“Hello”;
Long L = new Long(100000);
boolean done = false;
final double pi = 3.14159265358979323846;
Employee joe = new Employee();
char [] a = new char[3];
Vector v = new Vector();
54
Compared with C/C++
[3]
• Java has no:
– pointers
– typedef
– preprocessor
– struct
– unions
– multiple inheritance
– goto
– operator overloading
– malloc
– …
55
Operators (same as C/C+
+) [3]
• ++,-- Auto increment/decrement
• +,- Unary plus/minus
• *,/ Multiplication/division
• % Modulus
• +,- Addition/subtraction
56
Array
s
• Single dimensional array declaration:
Example:
int[] a;
int []a;
int a[];
• At the time of declaration we can't specify the size otherwise we will get compile
time error.
• Example:
• int[] a; //valid
• int[5] a; //invalid
57
Two dimensional array
declaration:
• int[][] a;
• int [][]a;
• int a[][]; All are valid.(6 ways)
• int[] []a;
• int[] a[];
• int []a[];
int[][] a=new int[2][]; int[][] a=new int[2][3];
a[0]=new int[3];
a[1]=new int[2];
48
Array initialization
• Every array in java is an object hence we can
create by using new operator.
• Example:
int[] a=new int[3]; int[][] a={{10,20,30},{40,50}};
int[][] a=new int[2][];
a[0]=new int[3];
a[1]=new int[2];
59
60
Rules
• Rule 1:
At the time of array creation compulsory we should specify the size otherwise
we will
get compile time error .
int[] a=new int[3];
• Rule 2:
It is legal to have an array with size zero in
java. int[] a=new int[0];
• Rule 3:
No negative size
• Rule 4:
61
The allowed data types to specify array
62
63
64
Evaluation of Arithmetic
Expressions
• If we are applying any arithmetic operators
b/w 2 operands 'a' & 'b' the result type is
•max(int , type of a , type of
b)
65
%
• (a) 7 % 3 ⇒1
• (b) 12 % 15 ⇒ 12
• (c) -20 % 7 ⇒ -6
• (d) 5.9 % 1.2 ⇒ 1.1
• (e) 8 % 0 Throws an
• (f) 0.8 % 0.0 ⇒ NaN
ArithmeticException
66
67
Boolean Logical
Operators
68
• The logical Boolean operators, &, |, and ^, operate on boolean
values in the same way that they operate on the bits of an
integer. The logical ! operator inverts the Boolean state:
• !true == false and !false == true.
69
Short-Circuit Logical
Operators
• These operators gets the result of an logical
operator, evaluating the right-hand
operator only if required.
• For a logical AND (&&) operation, if the left hand (first)
operand is false, then the result is false irrespective of
the right hand (second) operand.
• Similarly for short-circuit OR (||), if the first value is true,
then second value is not evaluated.
70
• if (denom != 0 && num / denom > 10)
• if(c==1 & e++ < 100) d = 100;
71
72
Increment & Decrement
Operators
73
Shorthand
74
Ternary
Operators
• Syntax :
(Condition)?(expression 1):
(expression 2);
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
75
instanceOf
Operator
• This is a type-check operator.
• It checks whether a particular object is the
instance of a certain class or not.
• It returns true if the object is a member of the
class and false if not.
76
Precedence
77
• (4 + 5) * (8 / 4 - 2) - Ans
78
Control Statements
79
if statement
80
Example
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 5) == 0)
{
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
}
81
if-else statement
82
Example
public static void main(String[]
args) { Scanner read = new
Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 2) == 0)
{
System.out.println("We are inside the true-
block!"); System.out.println("Given number is
EVEN number!!");
}
else {
System.out.println("We are inside the false-
block!");
System.out.println("Given number is ODD
number!!"); 83
Nested if
statement
Syntax:
if(condition_1)
{ if(condition_2
){
inner if-block of statements;
...
}
...
}
if (num < 100) {
System.out.println("\nGiven number is below 100");
if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
}
else
System.out.println("Given number is not below 100");
System.out.println("\nWe are outside the if-block!!!"); 74
if-else if
statement
if (condition1) {
// Code block to execute if condition1 is true
} else if (condition2) {
// Code block to execute if condition2 is true
} else {
// Code block to execute if all conditions are false
85
86
if( num1>=num2 && num1>=num3)
System.out.println("\nThe largest number is " + num1) ;
else if (num2>=num1 && num2>=num3) System.out.println("\
nThe largest number is " + num2) ;
else
System.out.println("\nThe largest number is " + num3) ;
System.out.println("\nWe are outside the if-block!!!");
87
switch statement
88
• The expression must be of type byte, short, int, or char; or string each of
the values specified in
the case statements must be of a type compatible with the expression.
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
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;
case 3:
System.out.println("i is
three.");
break;
default:
System.out.println("i is greater
than 3.");
} 79
Iteration Statements
• while statement
• do-while
statement
• for statement
• for-each
statement
90
while statement
91
int num = 1;
while(num <= 10)
{
System.out.println(num);
num++;
}
Find the midpoint between
100 and 200
92
do-while
statement
93
int num = 1;
do {
System.out.println(num);
num++;
}while(num <= 10);
94
for statement
95
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
}
96
for-each statement
97
public static void main(String[] args) { Search an array using for each loop
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList)
{
System.out.println("i = "
+ i);
}
System.out.println("Statement after for-
each!");
}
98
class ForEach3 { for(int x[] : nums)
public static void main(String args[]) {
{ for(int y : x)
int sum = 0; {
int nums[][] = new int[3][5]; System.out.println("Value is: " + y);
sum += y;
for(int i = 0; i < 3; i++) }
for(int j=0; j < 5; j++) }
nums[i][j] = (i+1)*(j+1); System.out.println("Summation: "
+ sum);
}
}
99
Nested Loops
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
100
Java Jump Statements
101
break statement
int list[] = {10, 20, 30, 40, 50};
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
102
continue
statement
int list[] = {10, 20, 30, 40, 50};
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}
103
Labelled break &
continue
statement
104
class Break {
public static void main(String args[]) {
boolean t = true;
first:
{ second:
{ third: {
System.o
ut.printl
n("Befor
e the
break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second
block.");
}
}
}
105
return statement
• The return statement used to terminate a
method with or without a value.
• The return statement takes the execution
control to the calling function.
void showValue(int value) {
for(int i = 0; i <= value; i++) {
if(i == 5)
return;
System.out.println(i);
}
}
106
class OperatorExample
{
public static void main(String args[])
{ System.out.println(10<<2);
//10*2^2=10*4=40 System.out.println(10<<3);
//10*2^3=10*8=80 System.out.println(10>>2);
//10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
107
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit
(MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
108