Size
Data Type Meaning (in Range
Bytes)
byte 2’s complement integer 1 -128 to 127
short 2’s complement integer 2 -32K to 32K
int Integer numbers 4 -2B to 2B
-
2’s complement integer 9,223,372,036,
854,775,808
long 8
to
(larger values) 9,223,372,036,
854,775,807
Upto 7
float Floating-point 4 decimal
digits
Upto 16
double Double Floating-point 8 decimal
digits
a, b, c ..
char Character 2 A, B, C ..
@, #, $ ..
bool Boolean 1 True, false
Variables & Data Types
1. Variables
A variable is a container (storage area) used to hold data.
Each variable should be given a unique name (identifier).
package [Link];
public class Main {
public static void main(String[] args) {
// Variables
String name = "Aman";
int age = 30;
String neighbour = "Akku";
String friend = neighbour;
}
}
2. Data Types
Data types are declarations for variables. This determines the type and size of data associated with
There are 2 types of Data Types :
Primitive Data types : to store simple values
Non-Primitive Data types : to store complex values
Primitive Data Types
These are the data types of fixed size.
Non-Primitive Data Types
These are of variable size & are usually declared with a ‘new’ keyword.
Eg : String, Arrays
String name = new String("Aman");
int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
3. Constants
A constant is a variable in Java which has a fixed value i.e. it cannot be assigned a different value o
package [Link];
public class Main {
public static void main(String[] args) {
// Constants
final float PI = 3.14F;
}
}
size of data associated with variables which is essential to know since different data types occupy different sizes of
assigned a different value once assigned.
occupy different sizes of memory.
1. Conditional Statements ‘if-else’
The if block is used to specify the code to be executed if the condition specified in if is true, the else
int age = 30;
if(age > 18) {
[Link]("This is an adult");
} else {
[Link]("This is not an adult");
}
2. Conditional Statements ‘switch’
Switch case statements are a substitute for long if statements that compare a
variable to multiple values. After a match is found, it executes the
corresponding code of that value case.
The following example is to print days of the week:
int n = 1;
switch(n) {
case 1 :
[Link]("Monday");
break;
case 2 :
[Link]("Tuesday");
break;
case 3 :
[Link]("Wednesday");
break;
case 4 :
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6 :
[Link]("Saturday");
break;
default :
[Link]("Sunday");
}
cified in if is true, the else block is executed otherwise.
Loops
A loop is used for executing a block of statements repeatedly until a particular condition is satisfied
For Loop
The syntax of the for loop is :
for (initialization; condition; update) {
// body of-loop
}
for (int i=1; i<=20; i++) {
[Link](i);
}
While Loop
The syntax for while loop is :
while(condition) {
// body of the loop
initialization
}
int i = 0;
while(i<=20) {
[Link](i);
i++;
}
Do-While Loop
The syntax for the do-while loop is :
do {
// body of loop;
}
while (condition);
int i = 0;
do {
[Link](i);
i++;
} while(i<=20);
Homework Problems
1. Print all even numbers till n.
2. Run
for(; ;) {
[Link]("Apna College");
}
loop on your system and analyze what happens. Try to think of the reason for the output produced.
3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.
If the user enters 1 then keep taking input from the user for a student’s marks(out of 100).
If they enter 0 then stop.
If he/ she scores :
Marks >=90 -> print “This is Good”
89 >= Marks >= 60 -> print “This is also Good”
59 >= Marks >= 0 -> print “This is Good as well”
Because marks don’t matter but our effort does.
(Hint : use do-while loop but think & understand why)
BONUS
Qs. Print if a number is prime or not (Input n from the user).
[In this problem you will learn how to check if a number is prime or not]
Homework Solution (Lecture 3)
import [Link].*;
public class Conditions {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int operator = [Link]();
/**
* 1 -> +
* 2 -> -
* 3 -> *
* 4 -> /
* 5 -> %
*/
switch(operator) {
case 1 : [Link](a+b);
break;
case 2 : [Link](a-b);
break;
case 3 : [Link](a*b);
break;
case 4 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a/b);
}
break;
case 5 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a%b);
}
break;
default : [Link]("Invalid Operator");
}
}
ular condition is satisfied. A loop consists of an initialization statement, a test condition and an increment statement.
for the output produced.
arks(out of 100).
an increment statement.
Methods/Functions
A function is a block of code that performs a specific task.
Why are functions used?
1. If some functionality is performed at multiple places in software, then rather than writing the same cod
2. Functions make maintenance of code easy as we have to change at one place if we make future chan
3. Functions make the code more readable and easy to understand.
The syntax for function declaration is :
return-type function_name (parameter 1, parameter2, …… parameter n){ //function_body
}
return-type
The return type of a function is the data type of the variable that that function returns.
For eg - If we write a function that adds 2 integers and returns their sum then the return type of this
When a function does not return any value, in that case the return type of the function is ‘void’.
function_name
It is the unique name of that function.
It is always recommended to declare a function before it is used.
Parameters
A function can take some parameters as inputs. These parameters are specified along with their da
For eg- if we are writing a function to add 2 integers, the parameters would be passed like –
int add (int num1, int num2)
main function
The main function is a special function as the computer starts running the code from the beginning
Example :
package [Link];
public class Main {
//A METHOD to calculate sum of 2 numbers - a & b
public static void sum(int a, int b) {
int sum = a + b;
[Link](sum);
}
public static void main(String[] args) {
int a = 10;
int b = 20;
sum(a, b); // Function Call
}
}
han writing the same code, again and again, we create a function and call it everywhere. This helps reduce code red
ce if we make future changes to the functionality.
eter n){ //function_body
tion returns.
hen the return type of this function will be ‘int’ as we will return a sum that is an integer value.
the function is ‘void’.
ecified along with their data types.
d be passed like –
code from the beginning of the main function. Main function serves as the entry point for the program.
his helps reduce code redundancy.
he program.
An operator is a symbol that the
compiler to perform a specific
operation on operands.
Example : a + b = c
In the above example, 'a' and 'b'
are operands on which the '+'
operator is applied.
Types of operators :
1. Arithmetic Operators :
Arithmetic operators are used
to perform mathematical
operations such as addition,
division, etc on expressions.
Arithmetic operators cannot
work with Booleans.
% operator can work on floats
and doubles.
Let x=7 and y=2
Operator Description
+ (Addition) Used to add two numbers
Used to subtract the right-hand
- (Subtraction) side value from the left-hand side
value
* (Multiplication) Used to multiply two values.
Used to divide left-hand Value by
/ (Division)
right-hand value.
Used to print the remainder after
dividing the left-hand side value
% (Modulus) from
the right-hand side value.
Increases the value of operand
++ (Increment)
by 1.
Decreases the value of operand
-- (Decrement)
by 1.
2. Comparison Operators :
As the name suggests, these
operators are used to compare
two operands.
Let x=7 and y=2
Operator Description
Checks if two operands are
== (Equal to)
equal. Returns a boolean value.
Checks if two operands are not
!= (Not equal
equal. Returns a boolean value.
Checks if the left-hand side value
> (Greater than) is greater than the right-hand side
value. Returns a boolean value.
Checks if the left-hand side value
< (Less than) is smaller than the right-hand side
value. Returns a boolean value.
Checks if the left-hand side value
is greater than or equal to the
>=(Greater than or equal to)
right-hand side value. Returns a
boolean value.
Checks if the left-hand side value
is less than or equal to the right-
<= (Less than or equal to)
hand side value. Returns a
boolean value.
3. Logical Operators :
These operators determine the
logic in an expression
containing two or more values
or variables.
Let x = 8 and y =2
Returns true if both operands are
&& (logical and)
true.
Returns true if any of the operand
|| (logical or)
is true.
Returns true if the result of the
! (logical not)
expression is false and vice-versa
3. Bitwise Operators :
These operators perform the
operations on every bit of a
number.
Let x =2 and y=3. So 2 in
binary is 100, and 3 is 011.
Operator Description
1&1 =1, 0&1=0,1&0=0,1&1=1,
& (bitwise and)
0&0 =0
| (bitwise or) 1&0 =1, 0&1=1,1&1=1, 0&0=0
^ (bitwise XOR) 1&0 =1, 0&1=1,1&1=0, 0&0=0
This operator moves the value
<< (left shift) left by the number of bits
specified.
This operator moves the value
>> (right shift) left by the number of bits
specified.
Precedence of operators
The operators are applied and
evaluated based on
precedence. For example, (+, -)
has less precedence compared
to (*, /). Hence * and / are
evaluated first.
In case we like to change this
order, we use parenthesis ().
Example
x+y=9
x-y=5
x * y = 14
x/y=3
x%y=1
x++ = 8
y-- = 1
Example
x == y --> False
x != y --> True
x > y --> True
x < y --> False
x >= y --> True
x <= y -->False
x<y && x!=y --> True
x<y && x==y --> True
!(x<y && x==y) --> False
Example
(A & B) = (100 & 011) = 000
(A | B) = (100 | 011 ) = 111
(A ^ B) = (100 ^ 011 ) = 111
13<<2 = 52(decimal)
13>>2 = 3(decimal)
Associativity And Precedence
Associativity tells the direction of the execution of operators. It can either
be left to right or vice versa.
/ * -> L to R
+ - -> L to R
++, = -> R to L
Here is the precedence and associativity table which makes it easy for you
to understand these topics better:
Quick Quiz: How will you write the following expression in Java?
package [Link];
public class cwh_09_ch2_op_pre {
public static void main(String[] args) {
// Precedence & Associativity
//int a = 6*5-34/2;
/*
Highest precedence goes to * and /. They are then evaluated on the basis
of left to right associativity
=30-34/2
=30-17
=13
*/
//int b = 60/5-34*2;
/*
= 12-34*2
=12-68
=-56
*/
//[Link](a);
//[Link](b);
// Quick Quiz
int x =6;
int y = 1;
// int k = x * y/2;
int b = 0;
int c = 0;
int a = 10;
int k = b*b - (4*a*c)/(2*a);
[Link](k);
}
}
STRING METHODS IN JAVA
String Methods operate on Java Strings. They can be used to find the length of the string, convert to
lowercase, etc.
Some of the commonly used String methods are:
String name = “Harry”;
(Indexes of the above string are as follows: 0-H, 1-a, 2-r, 3-r, 4-y)
Method
1. length()
2. toLowerCase()
3. toUpperCase()
4. trim()
5. substring(int start)
6. substring(int start, int end)
7. replace(‘r’, ‘p’)
8. startsWith(“Ha”)
9. endsWith(“ry”)
10. charAt(2)
11. indexOf(“s”)
12. lastIndexOf(“r”)
13. equals(“Harry”)
[Link](“harry”)
Escape Sequence Characters :
The sequence of characters after backslash ‘\’ = Escape Sequence Characters
Escape Sequence Characters consist of more than one character but represent one character when
used within the strings.
Examples: \n (newline), \t (tab), \’ (single quote), \\ (backslash), etc.
package [Link];
public class cwh_14_string_methods {
public static void main(String[] args) {
String name = "Harry";
// [Link](name);
int value = [Link]();
//[Link](value);
//String lstring = [Link]();
//[Link](lstring);
//String ustring = [Link]();
//[Link](ustring);
//String nonTrimmedString = " Harry ";
//[Link](nonTrimmedString);
//String trimmedString = [Link]();
//[Link](trimmedString);
//[Link]([Link](1));
//[Link]([Link](1,5));
//[Link]([Link]('r', 'p'));
//[Link]([Link]("r", "ier"));
//[Link]([Link]("Har"));
//[Link]([Link]("dd"));
//[Link]([Link](4));
//String modifiedName = "Harryrryrry";
//[Link]([Link]("rry"));
//[Link]([Link]("rry", 4));
//[Link]([Link]("rry", 7));
//[Link]([Link]("Harry"));
[Link]([Link]("HarRY"));
[Link]("I am escape sequence\tdouble quote");
}
}
Description
Returns the length of String name. (5 in this case)
Converts all the characters of the string to the lower case
letters.
Converts all the characters of the string to the upper case
letters.
Returns a new String after removing all the leading and trailing
spaces from the original string.
Returns a substring from start to the end. Substring(3)
returns “ry”. [Note that indexing starts from 0]
Returns a substring from the start index to the end index. The
start index is included, and the end is excluded.
Returns a new string after replacing r with p. Happy is returned
in this case. (This method takes char as argument)
Returns true if the name starts with the string “Ha”. (True in this
case)
Returns true if the name ends with the string “ry”. (True in this
case)
Returns the character at a given index position. (r in this case)
Returns the index of the first occurrence of the specified
character in the given string.
Returns the last index of the specified character from the given
string. (3 in this case)
Returns true if the given string is equal to “Harry” false
otherwise [Case sensitive]
Returns true if two strings are equal, ignoring the case of
characters.
Relational and Logical Operators in Java
Relational Operators in Java :
Relational operators are used to evaluate conditions (true or false) inside the if statements. Some
examples of relational operators are:
== (equals)
>= (greater than or equals to)
> (greater than)
< (less than)
<= (less than or equals to)
!= (not equals)
Note: ‘=’ is used for an assignment whereas ‘==’ is used for equality check. The condition can be
either true or false.
Logical Operators :
Logical operators are used to provide logic to our Java programs.
There are three types of logical operators in Java :
&& - AND
|| - OR
! – NOT
AND Operator :
Evaluates to true if both the conditions are true.
Y && Y = Y
Y && N = N
N && Y = N
N && N = N
Convention: # Y – True and N - False
OR Operator :
Evaluates to true when at least one of the conditions is true.
Y || Y = Y
Y || N = Y
N || Y = Y
N || N = N
Convention: # Y – True and N - False
NOT Operator :
Negates the given logic (true becomes false and vice-versa)
!Y = N
!N = Y
package [Link];
public class cwh_17_logical {
public static void main(String[] args) {
[Link]("For Logical AND...");
boolean a = true;
boolean b = false;
// if (a && b){
// [Link]("Y");
// }
// else{
// [Link]("N");
// }
[Link]("For Logical OR...");
// if (a || b){
// [Link]("Y");
// }
// else{
// [Link]("N");
// }
[Link]("For Logical NOT");
[Link]("Not(a) is ");
[Link](!a);
[Link]("Not(b) is ");
[Link](!b);
}
}
Arrays In Java
Arrays in Java are like a list of elements of the same type i.e. a list of integers, a list of booleans e
1. Creating an Array (method 1) - with new keyword
int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
2. Creating an Array (method 2)
int[] marks = {98, 97, 95};
3. Taking an array as an input and printing its elements.
import [Link].*;
public class Arrays {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int size = [Link]();
int numbers[] = new int[size];
for(int i=0; i<size; i++) {
numbers[i] = [Link]();
}
//print the numbers in array
for(int i=0; i<[Link]; i++) {
[Link](numbers[i]+" ");
}
}
}
egers, a list of booleans etc.
Keyword
abstract
assert
boolean
break
byte
case
catch
char
class
continue
default
do
double
else
enum
extends
final
finally
float
for
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
sealed
permits
Usage
Specifies that a class or method will be implemented later, in a
subclass
Assert describes a predicate placed in a Java program to indicate
that the developer thinks that the predicate is always true at that
place.
A data type that can hold True and False values only
A control statement for breaking out of loops.
A data type that can hold 8-bit data values
Used in switch statements to mark blocks of text
Catches exceptions generated by try statements
A data type that can hold unsigned 16-bit Unicode characters
Declares a new class
Sends control back outside a loop
Specifies the default block of code in a switch statement
Starts a do-while loop
A data type that can hold 64-bit floating-point numbers
Indicates alternative branches in an if statement
A Java keyword is used to declare an enumerated type.
Enumerations extend the base class.
Indicates that a class is derived from another class or interface
Indicates that a variable holds a constant value or that a method will
not be overridden
Indicates a block of code in a try-catch structure that will always be
executed
A data type that holds a 32-bit floating-point number
Used to start a for loop
Tests a true/false expression and branches accordingly
Specifies that a class implements an interface
References other classes
Indicates whether an object is an instance of a specific class or
implements an interface
A data type that can hold a 32-bit signed integer
Declares an interface
A data type that holds a 64-bit integer
Specifies that a method is implemented with native (platform-
specific) code
Creates new objects
This indicates that a reference does not refer to anything
Declares a Java package
An access specifier indicating that a method or variable may be
accessed only in the class it’s declared in
An access specifier indicating that a method or variable may only be
accessed in the class it’s declared in (or a subclass of the class it’s
declared in or other classes in the same package)
An access specifier used for classes, interfaces, methods, and
variables indicating that an item is accessible throughout the
application (or where the class that defines it is accessible)
Sends control and possibly a return value back from a called
method
A data type that can hold a 16-bit integer
Indicates that a variable or method is a class method (rather than
being limited to one particular object)
A Java keyword is used to restrict the precision and rounding of
floating-point calculations to ensure portability.
Refers to a class’s base class (used in a method or class
constructor)
A statement that executes code based on a test value
Specifies critical sections or methods in multithreaded code
Refers to the current object in a method or constructor
Creates an exception
Indicates what exceptions may be thrown by a method
Specifies that a variable is not part of an object’s persistent state
Starts a block of code that will be tested for exceptions
Specifies that a method does not have a return value
This indicates that a variable may change asynchronously
Starts a while loop
The sealed keyword is used to declare a class as “sealed,” meaning
it restricts which classes can extend it.
The permits keyword is used within a sealed class declaration to
specify the subclasses that are permitted to extend it.