CSE 2006 - Programming in Java
Course Type: LP Credits: 3
Prepared by
Dr Komarasamy G
Senior Associate Professor
School of Computing Science and Engineering
VIT Bhopal University
Unit-1 Contents
• Java Introduction
• Java Hello World, Java JVM, JRE and JDK, Difference
between C & C++, Java Variables, Java Data Types,
Java Operators, Java Input and Output, Java
Expressions & Blocks, Java Comment.
• Java Flow Control
• Java if...else, Java switch Statement, Java for Loop,
Java for-each Loop, Java while Loop, Java break
Statement, Java continue Statement
Unit-1 Java Introduction/ Dr Komarasamy G 2
Feature C C++ Java
Developed By Dennis Ritchie Bjarne Stroustrup James Gosling
Year of Creation 1972 1985 1995
Procedural + Object-
Programming Paradigm Procedural Pure Object-Oriented
Oriented
Compiled to machine Compiled to machine Compiled to bytecode
Compilation
code code (runs on JVM)
Platform Dependency Platform-dependent Platform-dependent Platform-independent
Partial (optional Full (everything is
OOP Support No
OOP) object-based)
Automatic (Garbage
Memory Management Manual (malloc, free) Manual (new, delete)
Collection)
Pointers Yes Yes No (restricted access)
Exception Handling No Yes Yes
No (uses interfaces
Multiple Inheritance No Yes (via classes)
instead)
Moderate (due to
Speed Very fast Fast
JVM overhead)
Syntax Simplicity Simple Slightly complex Verbose but consistent
OS, embedded systems, Games, GUI apps, system Web apps, Android apps,
Use Cases
hardware software enterprise software
Standard Libraries Limited Richer than C Extensive (Java API)
Supported (JavaFX,
GUI Development Not supported Supported (Qt, etc.)
Unit-1 Java Introduction/ Dr Komarasamy G Swing) 3
Difference between C & C++
C C++
C was developed by Dennis Ritchie
C++ was developed by Bjarne
between the year 1969 and 1973 at
Stroustrup in 1979.
AT&T Bell Labs.
C does not support polymorphism, C++
encapsulation, and inheritance which supports polymorphism, encapsulation,
means that C does not support object and inheritance because it is an object
oriented programming. oriented programming language.
C is a subset of C++. C++ is a superset of C.
C contains 32 keywords. C++ contains 63 keywords.
C++ is known as hybrid language
For the development of code, C because C++ supports
supports procedural programming. both procedural and object oriented
programming paradigms.
Data and functions are separated in C
Data and functions are encapsulated
because it is a procedural programming
together in form of an object in C++.
language.
Unit-1 Java Introduction/ Dr Komarasamy G 4
Difference between C & C++
C C++
Data is hidden by the Encapsulation to
C does not support information hiding. ensure that data structures and
operators are used as intended.
Built-in & user-defined data types is
Built-in data types is supported in C.
supported in C++.
C is a function driven language because C++ is an object driven language
C is a procedural programming because it is an object oriented
language. programming.
Function and operator overloading is Function and operator overloading is
not supported in C. supported by C++.
C is a function-driven language. C++ is an object-driven language
Functions in C are not defined inside Functions can be used inside a
structures. structure in C++.
Namespace features are not present Namespace is used by C++, which avoid
inside the C. name collisions.
Unit-1 Java Introduction/ Dr Komarasamy G 5
Difference between C & C++
C C++
Header file used by C is stdio.h. Header file used by C++ is iostream.h.
Reference variables are not supported Reference variables are supported by
by C. C++.
Virtual and friend functions are not Virtual and friend functions are
supported by C. supported by C++.
C does not support inheritance. C++ supports inheritance.
Instead of focusing on data, C focuses C++ focuses on data instead of focusing
on method or process. on method or procedure.
C
C++ provides new operator for memory
provides malloc() and calloc() functions
allocation and delete operator for
for dynamic memory allocation,
memory de-allocation.
and free() for memory de-allocation.
Direct support for exception handling is Exception handling is supported by
not supported by C. C++.
Unit-1 Java Introduction/ Dr Komarasamy G 6
Difference between C & C++
C C++
scanf() and printf() functions are used cin and cout are used for input/output
for input/output in C. in C++.
C structures don’t have access
C ++ structures have access modifiers.
modifiers.
C follows the top-down approach C++ follows the Bottom-up approach
Strict type checking in done in C++. So
There is no strict type checking in C many programs that run well in C
programming language. compiler will result in many warnings
and errors under C++ compiler.
C does not support overloading C++ does support overloading
Unit-1 Java Introduction/ Dr Komarasamy G 7
Java Variables
• A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
• Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
• There are two types of data types in Java:
primitive and non-primitive
• A variable is the name of a reserved area allocated in memory.
• In other words, it is a name of the memory location. It is a
combination of "vary + able" which means its value can be changed.
int data=50; //Here data is variable
Unit-1 Java Introduction/ Dr Komarasamy G 8
Types of Variables
• There are three types of variables in Java:
• 1) Local Variable
• A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.
• A local variable cannot be defined with "static" keyword.
• 2) Instance Variable
• A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
• It is called an instance variable because its value is instance-specific and is
not shared among instances.
• 3) Static variable
• A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among
all the instances of the class. Memory allocation for static variables happens
only once when the class is loaded in the memory.
Unit-1 Java Introduction/ Dr Komarasamy G 9
Types of Variables
• Example to understand the types of variables in java
public class A
{
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
public static void main(String args[])
{
int data=50; //instance variable
}
}//end of class
Unit-1 Java Introduction/ Dr Komarasamy G 10
Types of Variables
1) Local Variable
• A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.
• A local variable cannot be defined with "static" keyword.
Example of Local Variable
File Name: LocalVariableExample.java
public class LocalVariableExample {
public static void main(String[] args)
{
int num = 10; // Local Variable Output:
System.out.println(" Variable: " + num); Variable: 10
}
}
Unit-1 Java Introduction/ Dr Komarasamy G 11
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static. It is called an instance variable because its value is instance-
specific and is not shared among instances.
File Name: InstanceVariableDemo.java
import java.io.*;
public class InstanceVariableDemo {
//Defining Instance Variables
public String name;
public int age=19;
//Creating a default Constructor initializing Instance Variable
public InstanceVariableDemo()
{
Output:
this.name = "Deepak";
Student Name is: Deepak
}
Age: 19
public static void main(String[] args)
{
// Object Creation
InstanceVariableDemo obj = new InstanceVariableDemo();
System.out.println("Student Name is: " + obj.name);
System.out.println("Age: "+ obj.age);
}
Unit-1 Java Introduction/ Dr Komarasamy G 12
}
• 3) Static variable
• A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
Example Static variable
class Student{
static int age; //static variable
}
public class StaticVariableExample{
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.age = 24;
Output:
s2.age = 21; S1's age is: 23
Student.age = 23; S2's age is: 23
System.out.println("S1\'s age is: " + s1.age);
System.out.println("S2\'s age is: " + s2.age);
}
} Unit-1 Java Introduction/ Dr Komarasamy G 13
Java Data Types
• Data types specify the different sizes and values that can be stored in
the variable. There are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
• Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
• Java Primitive Data Types
• In Java language, primitive data types are the building blocks of data
manipulation.
• These are the most basic data types available in Java language.
• Java is a statically-typed programming language.
• It means, all variables must be declared before its use. That is
why we need to declare variable's type and name.
Unit-1 Java Introduction/ Dr Komarasamy G 14
Java Data Types
Unit-1 Java Introduction/ Dr Komarasamy G 15
Java Data Types
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
1 byte = 8 bits
Unit-1 Java Introduction/ Dr Komarasamy G 16
Java Data Types
Boolean Data Type
• The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.
• Example: Boolean one = false
Byte Data Type
• The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.
• The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4 times
smaller than an integer. It can also be used in place of "int" data type.
• Example: byte a = 10, byte b = -20
Unit-1 Java Introduction/ Dr Komarasamy G 17
Java Data Types
Short Data Type
• The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.
• The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
• short s = 10000, short r = -5000
Int Data Type
• The int data type is a 32-bit signed two's complement integer. Its value-range
lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive).
Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647.
Its default value is 0.
• The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
• Example:
• int a = 100000, int b = -200000
Unit-1 Java Introduction/ Dr Komarasamy G 18
Java Data Types
Long Data Type
• The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used
when you need a range of values more than those provided by int.
• Example: long a = 100000L, long b = -200000L
Float Data Type
• The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of double)
if you need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as currency. Its
default value is 0.0F.
• Example: float f1 = 234.5f
Unit-1 Java Introduction/ Dr Komarasamy G 19
Java Data Types
Double Data Type
• The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.
• Example:
• double d1 = 12.3
Char Data Type
• The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is
used to store characters.
• Example:
• char letterA = 'A'
Unit-1 Java Introduction/ Dr Komarasamy G 20
Java Operators
• Operators are symbols that perform operations on variables and
values. For example, + is an operator used for addition,
while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
Unit-1 Java Platform Overview /
21
Dr Komarasamy G
Java Operators
• 1. Java Arithmetic Operators
• Arithmetic operators are used to perform arithmetic operations on
variables and data.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x
https://www.w3schools.com/java/java_operators.asp
Unit-1 Java Platform Overview /
22
Dr Komarasamy G
Java Operators
• Java Logical Operators
• Logical operators are used to determine the logic between
variables or values:
Operator Name Description Example
&& Logical and Returns true if both statements x < 5 && x < 10
are true
|| Logical or Returns true if one of the x < 5 || x < 4
statements is true
! Logical not Reverse the result, returns false !(x < 5 && x < 10)
if the result is true
Unit-1 Java Platform Overview /
23
Dr Komarasamy G
Java Operators
// Java Arithmetic operations
import java.io.*;
class arith
{ public static void main(String args[])
{try{
DataInputStream din=new DataInputStream(System.in);
System.out.println("Enter the 2-no's");
int i=Integer.parseInt(din.readLine());
int j=Integer.parseInt(din.readLine());
System.out.println("addition is" + (i+j));
System.out.println("subtraction is" + (i-j));
System.out.println("multiplication is" + (i*j));
System.out.println("divisionion is" + (i/j));
System.out.println("modulo division is" +(i%j));
}catch(Exception e) {}
}
} Unit-1 Java Platform Overview /
Dr Komarasamy G
24
Java Operators
• Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Unit-1 Java Introduction/ Dr Komarasamy G 25
Java Operators
More details
• https://www.javatpoint.com/operators-in-java
Unit-1 Java Introduction/ Dr Komarasamy G 26
Java Operators
• Java Unary Operator
• The Java unary operators require only one operand.
Unary operators are used to perform various operations i.e.:
• incrementing/decrementing a value by one
• negating an expression
• inverting the value of a boolean
Unit-1 Java Introduction/ Dr Komarasamy G 27
Java Operators
• Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10; Output:
System.out.println(x++);//10 (11) 10
System.out.println(++x);//12 12
System.out.println(x--);//12 (11) 12
System.out.println(--x);//10 10
}}
Unit-1 Java Introduction/ Dr Komarasamy G 28
Java Operators
• Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10; Output:
System.out.println(a++ + ++a);//10+12=22 22
System.out.println(b++ + b++);//10+11=21 21
}}
Unit-1 Java Introduction/ Dr Komarasamy G 29
Java Operators
• Java Unary Operator Example: ~ and !
public class OperatorExample{ Output:
public static void main(String args[]){ -11
int a=10; 9
int b=-10; false
boolean c=true; true
boolean d=false;
System.out.println(~a);
//-11 (minus of total positive value which starts from 0)
System.out.println(~b);
//9 (positive of total minus, positive starts from 0)
System.out.println(!c); //false (opposite of boolean value)
System.out.println(!d); //true
}} Unit-1 Java Introduction/ Dr Komarasamy G 30
Java Operators
• Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
Unit-1 Java Introduction/ Dr Komarasamy G 31
Java Operators
• Java Left Shift Operator
• The Java left shift operator << is used to shift all of the bits in a
value to the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{ Output:
public static void main(String args[]){ 40
System.out.println(10<<2);//10*2^2=10*4=40 80
System.out.println(10<<3);//10*2^3=10*8=80 80
System.out.println(20<<2);//20*2^2=20*4=80 240
System.out.println(15<<4);//15*2^4=15*16=240
}}
Unit-1 Java Introduction/ Dr Komarasamy G 32
Java Operators
• Java Right Shift Operator
• The Java right shift operator >> is used to move the value of the
left operand to right by the number of bits specified by the right
operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String args[]){ Output:
System.out.println(10>>2); //10/2^2=10/4=2 2
System.out.println(20>>2); //20/2^2=20/4=5 5
System.out.println(20>>3); //20/2^3=20/8=2 2
}}
Unit-1 Java Introduction/ Dr Komarasamy G 33
Java Operators
• Java Assignment Operator
• Java assignment operator is one of the most common
operators. It is used to assign the value on its right to the
operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4) Output:
b-=4;//b=b-4 (b=20-4) 14
System.out.println(a); 16
System.out.println(b);
}} Unit-1 Java Introduction/ Dr Komarasamy G 34
Java Operators
• Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a); Output:
a-=4;//13-4 13
System.out.println(a); 9
a*=2;//9*2 18
System.out.println(a); 9
a/=2;//18/2
System.out.println(a);
}}
Unit-1 Java Introduction/ Dr Komarasamy G 35
Java Operators
• Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
Unit-1 Java Introduction/ Dr Komarasamy G 36
Java Operators
• After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}} Output:
20
Unit-1 Java Introduction/ Dr Komarasamy G 37
Java Expressions
• What is statement in Java?
• In Java, a statement is an executable instruction that tells the
compiler what to perform. It forms a complete command to be
executed and can include one or more expressions. A sentence
forms a complete idea that can include one or more clauses.
• Expression Statements
• Expression is an essential building block of any Java program
• . Generally, it is used to generate a new value. Sometimes, we
can also assign a value to a variable
• . In Java, expression is the combination of values,
variables, operators, and method calls.
Unit-1 Java Introduction/ Dr Komarasamy G 38
Java Expressions
• There are three types of expressions in Java:
• Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2.
• Note that the expression enclosed in the parentheses will be evaluate first,
after that rest of the expression.
• Expressions that assign a value.
• For example, number = 90, pi = 3.14.
• Expression that neither produces any result nor assigns a value.
• For example, increment or decrement a value by using increment or
decrement operator respectively, method invocation, etc.
• These expressions modify the value of a variable or state (memory) of a
program. For example, count++, int sum = a + b;
• The expression changes only the value of the variable sum. The value of
variables a and b do not change, so it is also a side effect.
Unit-1 Java Introduction/ Dr Komarasamy G 39
Java Expressions
• 1. Arithmetic Expressions
• An arithmetic expression uses arithmetic operators to perform mathematical
calculations.
• Example:
public class ArithmeticExpression {
public static void main(String[] args) {
int a = 10, b = 5, c = 2;
int sum = a + b; // Addition
int product = a * c; // Multiplication
int complex = (a + b) * c; // Combined
System.out.println("Sum: " + sum); // 15
System.out.println("Product: " + product); // 20
System.out.println("Complex: " + complex); // 30
}
}
Unit-1 Java Introduction/ Dr Komarasamy G 40
Java Expressions
• 2. Relational Expressions
• Relational expressions compare two values and return a boolean result (true
or false).
• Example:
public class RelationalExpression {
public static void main(String[] args) {
int x = 10, y = 20;
boolean isGreater = x > y; // false
boolean isEqual = x == y; // false
System.out.println("x > y: " + isGreater); // false
System.out.println("x == y: " + isEqual); // false
}
}
Unit-1 Java Introduction/ Dr Komarasamy G 41
Java Expressions
• 3. Logical Expressions
• Logical expressions combine multiple conditions using logical operators (&&,
||, !).
• Example:
public class LogicalExpression {
public static void main(String[] args) {
int a = 5, b = 10;
boolean bothConditions = (a < b) && (b > 0); // true
boolean eitherCondition = (a > b) || (b > 0); // true
System.out.println("Both conditions are true: " + bothConditions); // true
System.out.println("Either condition is true: " + eitherCondition); // true
}
}
Unit-1 Java Introduction/ Dr Komarasamy G 42
Java Expressions
• 4. Assignment Expressions
• An assignment expression assigns a value to a variable.
• Example:
public class AssignmentExpression {
public static void main(String[] args) {
int a = 10; // Assignment
a += 5; // a = a + 5
System.out.println("Value of a: " + a); // 15
}
}
Unit-1 Java Introduction/ Dr Komarasamy G 43
Java Comment
1. Single-Line Comment (//)
• Used to comment a single line.
Example:
// This is a single-line comment int age = 20; // Declare age
2. Multi-Line Comment (/* ... */)
• Used to comment multiple lines.
Example:
/* This is a multi-line comment It can span multiple lines */ int x = 10;
3. Documentation Comment (/** ... */)
• Used to generate JavaDocs (HTML documentation for classes and
methods).
Example:
• /** * This class represents a student. * It stores name and age. */
public class Student { String name; int age; }
Note: JavaDoc comments must be placed just before class, method,
or field declarations. Unit-1 Java Introduction/ Dr Komarasamy G 44
Java Comment
Comment Type Syntax Usage
Single-line // Short explanations, inline notes
Multi-line /* ... */ Block comments
Documentation /** ... */ For JavaDoc documentation
Unit-1 Java Introduction/ Dr Komarasamy G 45
Summary
• Java Hello World example
• Java JVM, JRE and JDK
• Difference between C ,C++ and Java
• Java Variables
• Java Data Types
• Java Operators
• Java Input and Output
• Java Expressions & Blocks
• Java Comment
Unit-1 Java Introduction/ Dr Komarasamy G 46