Java Module 2
Java Module 2
1.1. If/Else/Else If
The if/else statement is the most basic of control structures, but can also be considered the
very basis of decision making in programming.
While if can be used by itself, the most common use-scenario is choosing between two paths
with if/else:
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
Theoretically, we can infinitely chain or nest if/else blocks but this will hurt code
readability, and that's why it's not advised.
1.3. Switch
If we have multiple cases to choose from, we can use a switch statement.
int count = 3;
switch (count) {
case 0:
System.out.println("Count is equal to 0");
break;
case 1:
System.out.println("Count is equal to 1");
break;
default:
System.out.println("Count is either negative, or higher than
1");
break;
}
Three or more if/else statements can be hard to read. As one of the possible workarounds, we
can use switch, as seen above.
And also keep in mind that switch has scope and input limitations that we need to remember
before using it.
1.5. Break
We need to use break to exit early from a loop.
Let's see a quick example:
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Here, we are looking for a value of i, and we want to stop looking once we've found value of
i is 4.
A loop would normally go to completion, but we've used break here to short-circuit that and
exit early.
1.6. Continue
Simply put, continue means to skip the rest of the loop we're in:
for (int i = 0; i < 10; i++) {
if (i == 4) {
All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).
continue;
}
System.out.println(i);
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
2. Arrays
An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.
Example
String[] arrayx = new String[100]; //Declare and Allocate
or
The new keyword is crucial to creating an array. Without using it, we cannot make array
reference variables.
Arrays in Java are non-primitive data types that store elements of a similar data type in the
memory. Arrays in Java can store both primitive and non-primitive types of data in it. There
are two types of arrays, single-dimensional arrays have only one dimension, while multi-
dimensional have 2D, 3D, and nD dimensions.
In this digital world, storing information is a very crucial task to do as a programmer. Every
little piece of information needs to be saved in the memory location for future use. Instead of
storing hundreds of values in different hundreds of variables, using an array, we can store all
these values in just a single variable. To use that data frequently, we must assign a name,
which is done by variable.
An array is a homogenous non-primitive data type used to save multiple elements (having
the same data type) in a particular variable.
Arrays in Java can hold primitive data types (Integer, Character, Float, etc.) and non-
primitive data types (Object). The values of primitive data types are stored in a memory
location, whereas in the case of objects, it's stored in heap memory.
Assume you have to write a code that takes the marks of five students. Instead of creating
five different variables, you can just create an array of lengths of five. As a result, it is so easy
to store and access data from only one place, and also, it is memory efficient.
All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created.
An array of 10 elements
Each item in an array is called an element, and each element is accessed by its numerical
index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.
The following program, ArrayExample, creates an array of integers, puts some values in the
array, and prints each value to standard output.
class ArrayExample {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
Like declarations for variables of other types, an array declaration has two components: the
array's type and the array's name. An array's type is written as type[], where type is the
data type of the contained elements; the brackets are special symbols indicating that this
variable holds an array. The size of the array is not part of its type (which is why the brackets
All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).
are empty). An array's name can be anything you want, provided that it follows the rules and
conventions as previously discussed in the naming section. As with variables of other types,
the declaration does not actually create an array; it simply tells the compiler that this variable
will hold an array of the specified type.
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the brackets after the array's name:
However, convention discourages this form; the brackets identify the array type and should
appear with the type designation.
If this statement is missing, then the compiler prints an error like the following, and
compilation fails:
The next few lines assign values to each element of the array:
One dimensional array can be of either one row and multiple columns or multiple rows and
one column. For instance, a student's marks in five subjects indicate a single-dimensional
array.
Example:
int marks[] = {56, 98, 77, 89, 99};
During the execution of the above line, JVM (Java Virtual Machine) will create five blocks at
five different memory locations representing marks[0], marks[1], marks[2], marks[3],
and marks[4].
We can also define a one-dimensional array by first declaring an array and then performing
memory allocation using the new keyword.
class MultiDimArrayExample {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Sahayaraj", "Inbaselvi"}
};
// Mr. Sahayaraj
System.out.println(names[0][0] + names[1][0]);
// Ms. Inbaselvi
System.out.println(names[0][2] + names[1][1]);
}
}
System.out.println(anArray.length);
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse
order. Here, you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.
But, it is recommended to use the Java for-each loop for traversing the elements of array and
collection because it makes the code readable.
Advantages
It makes the code more readable.
It eliminates the possibility of programming errors.
Syntax:
for(data-type variable : array | collection)
{
// Code to be executed
}
Example:
class EnhancedForEx {
public static void main(String[] args)
{
// Declaring and initializing the integer array
// Custom integer entries in an array
int[] array = { 1, 2, 3, 4, 5, 6 };
4. Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes.
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring() etc.
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
By string literal
By new keyword
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Example:
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " +
txt.length());
Example:
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
Example
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
Note
Java counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third and so on.
5. Wrapper Classes
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known
as autoboxing and vice-versa unboxing.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
char ch = 'j';
}
}
import java.util.Scanner;
public class EvenOdd1 {
public static void main(String[] args) {
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}
PE 2.3 – Java program to Check whether a number is even or odd using Ternary Operator
The meaning of ternary is composed of three parts. The ternary operator (? :) consists of three
operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned
to the variable. It is the only conditional operator that accepts three operands. It can be used instead of
the if-else statement. It makes the code much more easy, readable, and shorter.
import java.util.Scanner;
}
}
PE 2.4 – Java program to check and print positive, negative and zero (using if-elseif-else)
class CheckPNZMain {
public static void main(String[] args) {
int number = 0;
int num = 5;
for(int i = 1; i <= 10; ++i)
{
System.out.printf("%d x %d = %d \n", num, i, num * i);
}
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
PE 2.8 – Java program to check whether the given number is palindrome or not
import java.util.Scanner;
class PalindromeNumber{
public static void main(String args[]){
int r,sum=0,temp, n;
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number");
n = myObj.nextInt();
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number");
else
System.out.println("not palindrome");
}
}
import java.util.*;
class CheckString {
public static void main(String[] args) {
Scanner xx = new Scanner(System.in);
String ip = xx.nextLine();
int len = ip.length();
System.out.println("The given string '"+ip+"' has "+len+"
Characters.");
}
}
PE 2.10 – Java program to print the character at the given position of the string
import java.util.Scanner;
public class CharPos {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
int pos = input.nextInt();
System.out.println("The character at the position " + pos +
" is '"+ str.charAt(pos-1)+"'.");
}
}
import java.util.Scanner;
class FactorialProgram{
public static void main(String args[]){
int i,fact=1;
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number");
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
import java.util.Scanner;
public class LargestNumberTernaryOp
{
public static void main(String[] args)
{
int a, b, c, largest, temp;
//object of the Scanner class
Scanner sc = new Scanner(System.in);
//reading input from the user
System.out.println("Enter the first number:");
a = sc.nextInt();
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter the third number:");
c = sc.nextInt();
//comparing a and b and storing the largest number in a temp
variable
temp=a>b?a:b;
//comparing the temp variable with c and storing the result in the
variable
largest=c>temp?c:temp;
//prints the largest number
System.out.println("The largest number is: "+largest);
} }
PE 2.13 – Java program to print the Factors of the given Positive Number
import java.util.*;
class FactOfNum {
public static void main(String[] args) {
Scanner xx = new Scanner(System.in);
int number = xx.nextInt();
System.out.print("Factors of " + number + " are: ");
for (int i = 1; i <= number; ++i) {
// if number is divided by i, i is the factor
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
class FactOfNegNum {
public static void main(String[] args) {
int number = -25; // negative number
System.out.print("Factors of " + number + " are: ");
// run loop from -ve number to +ve number
for(int i = number; i <= Math.abs(number); ++i) {
// skips the iteration for i = 0
if(i == 0) {
continue;
}
else {
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
}
PE 2.16 – Java program to print month name for the given number using Switch Case
PE 2.17 – Java program to check and print check Vowel or Consonant using Switch Case
default:
System.out.println("Default statement");
}
}
}
import java.util.Scanner;
public class example {
public static void main(String[] args) {
int a,b;
System.out.println("Enter a and b");
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
// Condition b = 2
case 2:
System.out.println("b is 2");
break;
// Condition b = 3
case 3:
System.out.println("b is 3");
break;
}
break;
// Condition a = 2
case 2:
System.out.println("a is 2");
break;
// Condition a == 3
case 3:
System.out.println("a is 3");
break;
default:
System.out.println("default statement printed");
break;
}
}
}
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
import java.util.Scanner;
class DWexample {
public static void main(String[] args) {
int sum = 0;
int number = 0;
import java.util.*;
PE 2.23 – Java program to print Multiplication table using Nested Do While loop
import java.util.*;
class ArrayExample {
public static void main(String[] args) {
Scanner xx = new Scanner(System.in);
int j=0;
int can=0;
while(j<5)
{
can = j+1;
System.out.println("Enter the name for Candidate
"+can+":");
name[j] = xx.nextLine();
System.out.println("Enter the Department for Candidate
"+can+":");
department[j] = xx.nextLine();
j++;
}
can=0;
for (int i=0; i<5; i++)
{
can = i+1;
System.out.println("The name of Candidate "+can+" is
"+name[i]+" and the candidate belongs to the '"+department[i]+"'.");
}
}
}
import java.lang.Math;
public class Main {
public static void main(String[] args) {
int w=2, x=8;
double y = Math.pow(w, x);
double z = Math.sqrt(y);
System.out.println("Value of y is "+y);
System.out.println("Value of z is "+z);
}
}
class EnForEachExample{
public static void main(String args[]){
int arr[]={15,20,36,58};
int total=0;
for(int i:arr){
total=total+i;
}
System.out.println("Total: "+total);
}
}
PE 2.28 – Java program to print the elements of array that consists of vowels using for-loop
and for-each loop
class EnForExample {
public static void main(String[] args) {