Java Revision
Java Revision
https://www.ccbp.in/
Data Types in Java
In programming languages, every value or data has an associated type
known as data type. Java supports various data types. These data types are
categorized into,
Primitive Data Types Primitive data types are those that are predefined by
the programming language (Java).
boolean: In general, anything that can take one of two possible values is
considered a boolean. In Java, true and false are considered boolean
values.
boolean canLearn = true;
byte: The byte data type is used to store integers without any fractional
part whose values are in the range -128 to 127.
byte points = 100;
short : The short data type is used to store integers without any fractional
part whose values are in the range -32,768 to 32,767.
short number = 28745;
int: The int data type is used to store integers without any fractional part
whose values are in the range -2 to 2 -1.
31 31
long: The long data type is used to store integers without any fractional
part whose values are in the range -2 to 2 -1. The long values should
63 63
float: The float data type is used to store any number with a decimal
point. The float data type stores a value up to 7 point precision (ex:
12.1234567). The float values should contain the suffix 'f' or 'F’.
float height = 5.10f;
double: The double data type is used to store any number with a decimal
point. The double data type stores a value up to 16 point precision. The
double values may contain the suffix 'd' or 'D'.
double breadth = 9.2345D;
Non-Primitive Data Types These data types are used to store multiple
values. Non-primitive data types are defined by the programmer. In Java
programming, all non-primitive data types are simply called objects. Some
commonly used non-primitive data types are,
String
Array
Class
Array: In Java, an array is an object used to store similar data type values.
In Java, the number of elements that an array can store is always fixed.
int[] arr = {60, 25, 20, 15, 30};
Conditional Statements
Conditional Statement: Conditional Statement allows us to execute a
block of code only when a specific condition is true.
If…Else Statements: When an if...else conditional statement is used,
the if block of code executes when the condition is true, otherwise the
else block of code is executed.
int token = 20;
if (token == 20)
System.out.println("Collect Water Bottle");
else
System.out.println("Invalid Token");
// Output is:
Collect Water Bottle
Else if Statement: Java provides an else if statement to have multiple
conditional statements between if and else. The else if statement is
optional. We can add any number of else if statements after if
conditional block.
int token = 20;
if (token == 10)
System.out.println("Collect Chips");
else if(token == 20)
System.out.println("Collect Soft Drink");
else
System.out.println("Invalid Token");
// Output is:
Collect Soft Drink
Switch: A switch block can have multiple case or default labels. The
switch statement allows us to execute a block of code among many cases.
switch (100 / 10) {
case 10:
System.out.println("Ten");
break;
case 20:
System.out.println("Twenty");
break;
default:
System.out.println("Other Number");
break;
}
// Output is:
Ten
Length of String: The string object has a length() method that returns
the number of characters in a given string.
String name = "Rahul";
int strLength = name.length();
System.out.println(strLength); // 5
String Indexing: We can access an individual character in a string using
their positions. These positions are also called indexes. The charAt()
method is used to get the character at a specified index in a string.
String name = "Rahul";
char firstLetter = name.charAt(0);
System.out.println(firstLetter); // R
Slicing to end
String message = "Welcome to Java";
String part = message.substring(11);
System.out.println(part); // Java
Calculations in Java
Addition: Addition is denoted by + sign. It gives the sum of two numbers.
System.out.println(2 + 5); // 7
System.out.println(1 + 1.5); // 2.5
Following are the methods, used to read different types of inputs from the
user:
Method Description
nextInt() Reads an int value
nextLong() Reads a long value
nextFloat() Reads a float value
nextBoolean( Reads a boolean value
)
next() Reads a String value only until a space(" ") is encountered
nextLine() Reads a String value till the end of line
nextDouble() Reads a double value
nextShort() Reads a short value
nextByte() Reads a byte value
Printing the Output In Java, we have different methods available to print
the output to the console.
The print() accepts a value as a parameter and prints text on the console.
It prints the result in the same line.
System.out.print("Hello ");
System.out.print("Rahul");
// Output is:
Hello Rahul
Multi-line comments start with /* and end with */. In between these, we
can write any number of statements.
/* This is a
Multi-line Comment */
String Methods
Method Syntax Usage
trim() str.trim(); removes all the leading and
trailing spaces of the given
string and returns a new string.
toLowerCase() str.toLowerCase(); converts each character of the
given string to lowercase and
returns a new string.
toUpperCase() str.toUpperCase(); converts each character of the
given string to uppercase and
returns a new string.
startsWith() str.startsWith(value); returns true if the given string
starts with the specified value.
Otherwise, false is returned.
Method Syntax Usage
endsWith() str.endsWith(value); returns true if the given string
ends with the specified value.
Otherwise, false is returned.
replace() str.replace(old, latest); replaces all the occurrences of
the old character/substring
with the latest
character/substring and returns
a new string.
replaceFirst() str.replaceFirst(old, latest); returns a new string after
replacing the first occurrence
of the old substring with the
latest substring.
split() str.split(separator); used to split the string at the
specified separator. It returns
an array of substrings.
join() String.join(delimiter, str1, joins the given elements with
str2, ...); the specified delimiter and
returns a new string.
equals() str1.equals(str2); It returns true if the given
strings are equal. Otherwise
false is returned.
equalsIgnoreCase() str1.equalsIgnoreCase(str2); It works similar to equals(),
but ignores the case difference
between the strings.
compareTo() str1.compareTo(str2); used to compare two strings
based on the Unicode values.
compareToIgnoreCase( str1.compareToIgnoreCase(str2); It works similar to the
) compareTo() but ignores the
case difference between the
strings.
do...while loop: It is similar to the while loop. The only difference is that in
the do...while loop, the check is performed after the do...while block
of code has been executed.
do {
System.out.println("Line Executed");
} while (3 > 10);
// Output is:
Line Executed
Arrays
Array: In Java, an array is an object used to store similar data type values.
In Java, the number of elements that an array can store is always fixed.
Accessing Array Elements: We can access the elements of an array using
these index values.
int[] arr = {12, 4, 5, 2, 5};
System.out.println(arr[0]); //12
Creating an Array using a new Keyword: We can also create the array
using new keyword. We can create an array of required length and later
assign the values.
int[] arr;
arr = new int[3];
Length of an Array: In Java, we can find the array length by using the
attribute length.
int[] arr = {12, 4, 5, 2, 5, 7};
System.out.println(arr.length); // 6
Ascending Order
Methods
Methods: Java doesn't have independent functions because every Java
function belongs to a class and is called a Method.
Method Declaration: A Method must be declared before it is used
anywhere in the program.
accessModifier static returnType methodName() {
// method body
}
Calling a Method: The block of code in the methods is executed only when
the method is called.
static void greet() {
System.out.println("Hello, I am in the greet method");
}
public static void main(String[] args){
greet();
}
// Output is:
Hello, I am in the greet method
Nested Loops
Nested Loops: If a loop exists inside the body of another loop, it is called a
nested loop. The inner loop will be executed one time for each iteration of
the outer loop.
Example 1:
for (int i = 0; i < 2; i = i + 1) {
System.out.println("Outer: " + i);
for (int j = 0; j < 2; j = j + 1)
System.out.println(" Inner: " + j);
}
System.out.println("After nested for loops");
// Output is:
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
After nested for loops
Example 2:
for (int i = 0; i < 2; i = i + 1) {
System.out.println("Outer For Loop: " + i);
int counter = 0;
while (counter < 2) {
System.out.println(" Inner While Loop: " + counter);
counter = counter + 1;
}
}
//Output is:
Outer For Loop: 0
Inner While Loop: 0
Inner While Loop: 1
Outer For Loop: 1
Inner While Loop: 0
Inner While Loop:1
Loop Control Statements: The statement which alters the flow of control
of a loop is called a Loop Control Statement.
Name Usage
Break break keyword is used to stop the execution of the loop.
Continue continue keyword is used to skip the current execution of the loop.
Break (in nested break keyword in the inner loop stops the execution of the inner
loops) loop.
Adding Primitive Data Types: ArrayList can only store objects. To use
primitive data types, we have to convert them to objects. In Java, Wrapper
Classes are can be used to convert primitive types (int, char, float, etc) into
corresponding objects.
Autoboxing: The conversion of primitive types into their corresponding
wrapper class objects is called Autoboxing. Unboxing: The conversion of
wrapper class objects into their corresponding primitive types is called
Unboxing.
Method Syntax Usage
add() arrList.add(index, used to add a single element to the ArrayList.
element);
get() arrList.get(index); used to access an element from an ArrayList.
set() arrList.set(index, used to replace or modify an element in the
element); ArrayList.
remove(index) arrList.remove(index); removes the element at the specified position, i.e
index, in the ArrayList.
remove(object) arrayList.remove(obj); removes the first occurrence of the specified
element from the ArrayList if it is present.
Remains unchanged if not present
clear() arrList.clear() It completely removes all of the elements from
the ArrayList.
Method Syntax Usage
size() arrList.size() used to find the size of an ArrayList.
indexOf() arrList.indexOf(obj); returns the index of the first occurrence of the
specified element in the ArrayList. Returns -1 if
not present
Ascending order
HashSet
HashSet: The HashSet is also an unordered collection of elements. The
HashSet stores only unique elements and duplicate elements are not
allowed.
HashSet<Type> hset = new HashSet<>();
Method Syntax Usage
add() hset.add(element); to add a single element to the HashSet.
remove() hset.remove(element); removes an element from the HashSet.
clear() hset.clear() removes all the elements from a HashSet.
contains() hset.contains(element); checks if an element is present in a given HashSet.
size() hset.size() used to find the size of a HashSet.
HashSet Operations
Union: The addAll() method can be used to perform the union of two
sets. Syntax: hset1.addAll(hset2);
HashSet<Integer> hset1 = new HashSet<>();
HashSet<Integer> hset2 = new HashSet<>();
hset1.add(3);
hset1.add(32);
hset1.add(8);
hset2.add(8);
hset2.add(32);
hset2.add(30);
hset1.addAll(hset2);
System.out.println(hset1);
// Output is:
on: [32, 3, 8, 30]
SuperSet: A superset of any given set is defined as the set which contains
all the elements present in the given set. The containsAll() can be used
to check if the given set is the superset of any other set.
hset1.containsAll(hset2);
HashMap
HashMap: The HashMap is also an unordered collection of elements.
HashMap stores the data in key/value pairs. Here, keys should be unique
and a value is mapped with the key. HashMap can have duplicate values.
HashMap<KeyType, ValueType> hmap = new HashMap<>();
Method Syntax Usage
put() hmap.put(key, value); used to add/update an element to the
HashMap.
get() hmap.get(key); used to access the value mapped with a
specified key in a HashMap.
Method Syntax Usage
replace() hmap.replace(key, replaces the old value of the specified key
newValue); with the new value.
remove() hmap.remove(key); used to remove an element from a
HashMap.
clear() hmap.clear(); to remove all the elements from a
HashMap.
keySet() hmap.keySet(); returns a HashSet of all the keys of a
HashMap.
values() hmap.values(); to get all the values mapped to the keys in a
HashMap.
entrySet() hmap.entrySet(); used to get the elements of a HashMap.
size() hmap.size(); used to find the size of a HashMap.
containsKey() hmap.containsKey(key); It returns true if the HashMap contains the
specified key. Otherwise false is returned.
containsValue( hmap.containsValue(value); It returns true if the HashMap contains the
) specified value. Otherwise false is returned.
putAll() hmap2.putAll(hmap1); used to copy all the elements from a
HashMap to another HashMap.
Iterating a HashMap
HashMap<String, Integer> playersScore = new HashMap<>();
playersScore.put("Robert", 145);
playersScore.put("James", 121);
playersScore.put("Antony", 136);
playersScore.put("John", 78);
for (Map.Entry<String, Integer> entry : playersScore.entrySet())
System.out.printf("%s:%d\n", entry.getKey(), entry.getValue());
// Output is:
James:121
Robert:145
John:78
Antony:136
Math Methods
Methods Description
pow() It calculates the exponents and returns the result.
round() It rounds the specified value to the closest int or long value and returns it.
Methods Description
min() Returns the numerically lesser number between the two given numbers.
max() Returns the numerically greater number between the two given numbers.
abs() Returns the absolute value of the given number
Type Conversions
Type Conversion: Type conversion is a process of converting the value of
one data type (int, char, float, etc.) to another data type. Java provides two
types of type conversion :
Example 2:
char a = 'A';
String str = Character.toString(a);
System.out.println(str); // A
Similarly, for other primitive data types as given the table below,
Primitive Data
Syntax
Type
byte Byte.parseByte()
short Short.parseShort()
int Integer.parseInt()
long Long.parseLong()
float Float.parseFloat()
double Double.parseDouble()
boolean Boolean.parseBoolean()
Class Attributes: Attributes whose values stay common for all the objects
are modelled as class Attributes. The static keyword is used to create the
class attributes.
class Cart {
static int flatDiscount = 0;
static int minBill = 100;
}
Accessing Class Attributes: The class attributes can also be accessed using
the dot (.) notation. We can access the class attributes directly using the
class name.
class Cart {
static int flatDiscount = 0;
static int minBill = 100;
}
class Base {
public static void main(String[] args) {
System.out.println(Cart.flatDiscount);
System.out.println(Cart.minBill);
}
}
// Output is:
0
100
Class Methods: In Java, class methods are also called static methods. The
static keyword is used to create the class methods.
class Cart {
static int flatDiscount = 0;
static int minBill = 100;
static void updateFlatDiscount(int newFlatDiscount) {
flatDiscount = newFlatDiscount;
}
}
Accessing Class Methods: The class methods can also be accessed using
the dot (.) notation. We can access the class methods directly using the
class name.
class Cart {
static int flatDiscount = 0;
static int minBill = 100;
static void updateFlatDiscount(int newFlatDiscount) {
flatDiscount = newFlatDiscount;
}
}
class Base {
public static void main(String[] args) {
Cart.updateFlatDiscount(50);
System.out.println(Cart.flatDiscount); // 50
}
}
OOPS
OOPS: Object-Oriented Programming System (OOPS) is a way of
approaching, designing, developing software that is easy to change.
Encapsulation: It is a process of wrapping related code and data together
into a single unit.
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Main {
public static void main(String[] args) {
Student student = new Student();
student.setAge(20);
System.out.println(student.getAge()); // 20
}
}
1. Compile-time polymorphism
2. Runtime polymorphism
1. Abstract classes
2. Interfaces
Abstract Classes and Methods Abstract Classes: The abstract keyword
is a non-access modifier, applied to classes and methods in Java. A class
which is declared with the abstract keyword is known as an abstract class.
abstract class ClassName {
// attributes and methods
}
We can also create a stream directly using the of() method of the Stream
interface.
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
Example 1:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie",
"Dave");
names.stream()
.filter(eachName -> eachName.length() > 4)
.forEach(name -> System.out.println(name));
// Output is:
Alice
Charlie
Example 2:
List<Integer> numbers = Arrays.asList(2, 5);
numbers.stream()
.map(eachNumber -> eachNumber * 2)
.forEach(number -> System.out.println(number));
// Output is:
4
10
Optionals
Optional Class: The Optional class is designed to be used as a return type
for methods that may or may not return a value. It provides several
methods to help prevent the NullPointerException.
Creating Optionals: The Optional class provides different methods to
create optionals.
1. empty()
2. of()
3. ofNullable()
Optional Methods:
Method Syntax Usage
isPresent() optional.isPresent(); used to check if an element is present in the
optional.
get() optional.get(); used to get the element in the optional. It
throws an exception if no element is present.
orElse() optional.orElse(); used to get a default value (constant value) if
the optional is empty.
orElseGet( optional.orElseGet(Supplier); used to get a default value (dynamic value) if
) the optional is empty.
Method Syntax Usage
ifPresent() optional.ifPresent(Consumer); used to perform specified operation on the
elements in the optional.
map() optional.map(Function); used to perform a specified operation on
elements in an optional and return a new
optional.
filter() optional.filter(Predicate); used to filter the elements in an optional based
on a specified condition and return a new
optional.
I/O Streams
Paths: In Java, the Path interface from java.nio.file package represents
a path to a file or directory in the file system. The paths are of two types:
1. Relative path
2. Absolute path
Relative Path: A relative path is a path that specifies the location of a file or
directory relative to the current working directory. Example: documents\
file.txt Absolute Path: An absolute path is a path that specifies the exact
location of a file or directory in the file system, starting from the root
directory. Example: /home/rahul/documents/file.txt
Finding Absolute Path using Java
File file = new File("file.txt");
System.out.println(file.getAbsolutePath());
// Output is:
/home/rahul/documents/file.txt
1. read()
2. readLine()
read(): The read() method reads a single character from a file. It returns
int data type.
// Text in the source.txt file
Hello World!
try {
BufferedReader br = new BufferedReader(new
FileReader("source.txt"));
char[] arr = new char[100];
br.read(arr);
System.out.println(arr); // Hello World!
br.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}