0% found this document useful (0 votes)
48 views

Java Module 2

This document discusses control structures and arrays in Java programming. It covers looping constructs like for, while, and do-while loops. It also covers conditional statements like if/else and switch statements. The document provides examples of using these control structures. Additionally, it discusses arrays in Java - how to declare, initialize, and access array elements. It notes that arrays allow storing multiple values of the same type in a single variable in an organized way.

Uploaded by

Piranava Guru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Java Module 2

This document discusses control structures and arrays in Java programming. It covers looping constructs like for, while, and do-while loops. It also covers conditional statements like if/else and switch statements. The document provides examples of using these control structures. Additionally, it discusses arrays in Java - how to declare, initialize, and access array elements. It notes that arrays allow storing multiple values of the same type in a single variable in an organized way.

Uploaded by

Piranava Guru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

BCSE103E – Computer Programming: JAVA

Course Faculty: Dr. Logesh R. (CADS–SENSE, VIT–Chennai)

Module 2: Looping Constructs and Arrays

1. Control and looping constructs


In the most basic sense, a program is a list of instructions. Control structures are
programming blocks that can change the path we take through those instructions.
In this tutorial, we'll explore control structures in Java.
There are three kinds of control structures:
 Conditional Branches, which we use for choosing between two or more paths. There
are three types in Java: if/else/else if, ternary operator and switch.
 Loops that are used to iterate through multiple values/objects and repeatedly run
specific code blocks. The basic loop types in Java are for, while and do while.
 Branching Statements, which are used to alter the flow of control in loops. There are
two types in Java: break and continue.

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.2. Ternary Operator


We can use a ternary operator as a shorthand expression that works like
an if/else statement.
Let's see our if/else example again:
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}

We can refactor the above if/else with a ternary as follows:


System.out.println(count > 2 ? "Count is higher than 2" : "Count is
lower or equal than 2");

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


While ternary can be a great way to make our code more readable, it isn't always a good
substitute for if/else.

1.3. Switch
If we have multiple cases to choose from, we can use a switch statement.

Let's again see a simple example:

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.

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


1.4. Loops
We use loops when we need to repeat the same code multiple times in succession.
Let's see a quick example of comparable for, while and do–while type of loops.

1.4.1 For Loop Working and Example

Example of a For Loop


for (int i = 1; i <= 50; i++) {
System.out.println(i);
}

1.4.2 While Loop Working and Example

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


Example of a While Loop
int whileCounter = 1;
while (whileCounter <= 50) {
System.out.println(whileCounter);
whileCounter++;
}

1.4.3 Do–While Loop Working and Example

Example of a Do–While Loop


int whileCounter = 1;
do{
System.out.println(whileCounter);
whileCounter++;
}while(whileCounter <= 50);

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.

The above example skips when the value of i is 4.

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

String[] arrayx; //Declare


arrayx = new String[100]; //Allocate

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;

// allocates memory for 10 integers


anArray = new int[5];

// initialize the elements


anArray[0] = 100;
anArray[1] = 200;
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;

System.out.println("Element at index 0: " + anArray[0]);


System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
}
}
2.1 Declaring a Variable to Refer to an Array
The preceding program declares an array (named anArray) with the following line of code:

// 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.

Similarly, you can declare arrays of other types:

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:

// this form is discouraged


float anArrayOfFloats[];

However, convention discourages this form; the brackets identify the array type and should
appear with the type designation.

2.2 Creating, Initializing, and Accessing an Array


One way to create an array is with the new operator. The next statement in the
ArrayExample program allocates an array with enough memory for 10 integer elements
and assigns the array to the anArray variable.

// create an array of integers


anArray = new int[10];

If this statement is missing, then the compiler prints an error like the following, and
compilation fails:

ArrayExample.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element


anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth
Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);


System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


int[] anArray = {
100, 200, 300,
400, 500, 600,
700, 800, 900, 1000
};
Here the length of the array is determined by the number of values provided between braces
and separated by commas.

2.3 One dimensional and Multi-dimensional Arrays


There are two types of arrays in Java and they are:
One dimensional array − A single dimensional array of Java is a normal array where, the
array contains sequential elements (of same type)
Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two
dimensional array is an array of one dimensional arrays and a three dimensional array is an
array of two dimensional arrays.

2.3.1 One dimensional Arrays


An array that has only one subscript or one dimension is known as a single-dimensional
array. It is just a list of the same data type variables.

One dimensional Array – Example

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.

2.3.2 Multi-dimensional Arrays


A multi-dimensional array is just an array of arrays that represents multiple rows and
columns. These arrays include 2D, 3D, and nD types. 2D data like tables and matrices can be
represented using this type of array.

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


You can declare an array of arrays (also known as a multidimensional array) by using two or
more sets of brackets, such as String[][] names. Each element, therefore, must be accessed by
a corresponding number of index values.

In the Java programming language, a multidimensional array is an array whose components


are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the
rows are allowed to vary in length, as shown in the following MultiDimArrayExample
program:

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]);
}
}

The output from this program is:


Mr. Sahayaraj
Ms. Inbaselvi

Multi dimensional Array – Example

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


Finally, you can use the built-in length property to determine the size of any array. The
following code prints the array's size to standard output:

System.out.println(anArray.length);

3. Enhanced For Loop


Java Enhanced for-loop was introduced in java version 1.5 / J2SE 5.0 and it is also a control
flow statement that iterates a part of the program multiple times. This for-loop provides
another way for traversing the array or collections and hence it is mainly used for traversing
array or collections. This loop also makes the code more readable and reduces the chance of
bugs in the code. It is known as for-each loop because it traverses each element one by one.

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 };

// Accessing the element of array using for-each loop


for (int a : array) {
// Print all elements of an array
System.out.println(a);
}
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


Difference Between For-Loop and Enhanced For Loop
Normal for-loop Enhanced for-loop
This for-loop is present from JDK1 This for loop is present from JDK5
In a normal for-loop, we can increase the But enhanced for loop will execute in a
counter as per our wish by using sequential manner i.e counter will always
i=i+x( where x is any constant x=1,2,3…) increase by one.
We can only iterate on that container by
Using this for loop we can iterate on any
using this loop to implement the iterable
container object.
interface.
In this for-loop, we can iterate in both In the enhanced for-loop, we can iterate only
decrement or increment order. in increment order.
In the enhanced for-loop, we don’t have
In this for-loop, we can replace elements at
access to the index, so we cannot replace
any specific index.
elements at any specific index.
By using normal for-loop we can print array In the enhanced for-each loop, we can print
elements either in the original order or in array element only in the original order, not
reverse order. in reverse order
Example: Printing element in a 1D array
Example: Printing element in a 1D array
int[ ] x={1,2,3}; using for-each loop
for(int i=0;i<x.length;i++) int[ ] x={1,2,3};
{ for(int a : x)
System.out.println(x[i]); {
} System.out.println(a);
}
Example: Printing element in a 2D array Example: Printing element in a 2D array
using for loop using for-each loop
int[ ][ ] x={{1,2,3},{4,5,6}}; int[ ][ ] x={{1,2,3},{4,5,6}} ;
for(int i=0;i<x.length;i++) { for(int[ ] x1 :x){
for(int j=0; j<x[i].length;j++) { for(int x2 : x1) {
System.out.println(x[i][j]); System.out.println(x2);
} }
} }

4. Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes.

Example: Create a variable of type String and assign it a value.


String message = "Hello";

4.1. Java String Class


In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

char[] ch={'V','I','T',' ','U','n','i','v','e','r','s','i','t','y'};


String s=new String(ch);

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


The above is same as:

String s="VIT University";

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.lang.String class implements Serializable, Comparable and CharSequence


interfaces.

4.2. CharSequence Interface


The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java
by using these three classes.

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.

4.3. What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


4.3.1. How to create a string object?
There are two ways to create String object:

 By string literal
 By new keyword

4.3.1.1. String Literal


Java String literal is created by using double quotes. For Example:

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".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


4.3.1.2. By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable

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).

4.4. String Length


A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with the length()
method.

Example:
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " +
txt.length());

4.5. Other Popular String Methods


There are many string methods available, for example toUpperCase() and
toLowerCase().

Example:
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"

4.6. Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a specified
text in a string (including whitespace).

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.

4.7. All String Methods – For Reference


The String class has a set of built-in methods that you can use on strings.

Method Description Return Type


charAt() Returns the character at the specified index char
(position)

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


codePointAt() Returns the Unicode of the character at the int
specified index
codePointBefore() Returns the Unicode of the character before the int
specified index
codePointCount() Returns the number of Unicode values found in int
a string.
compareTo() Compares two strings lexicographically int
compareToIgnoreCase() Compares two strings lexicographically, int
ignoring case differences
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of boolean
characters
contentEquals() Checks whether a string contains the exact boolean
same sequence of characters of the specified
CharSequence or StringBuffer
copyValueOf() Returns a String that represents the characters String
of the character array
endsWith() Checks whether a string ends with the specified boolean
character(s)
equals() Compares two strings. Returns true if the boolean
strings are equal, and false if not
equalsIgnoreCase() Compares two strings, ignoring case boolean
considerations
format() Returns a formatted string using the specified String
locale, format string, and arguments
getBytes() Encodes this String into a sequence of bytes byte[]
using the named charset, storing the result into
a new byte array
getChars() Copies characters from a string to an array of void
chars
hashCode() Returns the hash code of a string int
indexOf() Returns the position of the first found int
occurrence of specified characters in a string
intern() Returns the canonical representation for the String
string object

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


isEmpty() Checks whether a string is empty or not boolean
lastIndexOf() Returns the position of the last found int
occurrence of specified characters in a string
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular boolean
expression, and returns the matches
offsetByCodePoints() Returns the index within this String that is int
offset from the given index by codePointOffset
code points
regionMatches() Tests if two string regions are equal boolean
replace() Searches a string for a specified value, and String
returns a new string where the specified values
are replaced
replaceFirst() Replaces the first occurrence of a substring that String
matches the given regular expression with the
given replacement
replaceAll() Replaces each substring of this string that String
matches the given regular expression with the
given replacement
split() Splits a string into an array of substrings String[]
startsWith() Checks whether a string starts with specified boolean
characters
subSequence() Returns a new character sequence that is a CharSequence
subsequence of this sequence
substring() Returns a new string which is the substring of a String
specified string
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the String
specified value

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


4.8. Format Specifiers – For Reference
There are multiple ways of formatting Strings in Java. The following Format Specifiers can be
used with System.out.printf() and System.out.format() to print the Strings in the
desired format.

Format Specifier Data Type Output


Returns Hex output of floating point
%a floating point (except BigDecimal)
number.
%b Any type "true" if non-null, "false" if null
%c character Unicode character
integer (incl. byte, short, int, long,
%d Decimal Integer
bigint)
%e floating point decimal number in scientific notation
%f floating point decimal number
decimal number, possibly in scientific
%g floating point notation depending on the precision
and value.
Hex String of value from hashCode()
%h any type
method.
%n none Platform-specific line separator.
integer (incl. byte, short, int, long,
%o Octal number
bigint)
%s any type String value
%t is the prefix for Date/Time
Date/Time (incl. long, Calendar, Date conversions. More formatting flags
%t
and TemporalAccessor) are needed after this. See Date/Time
conversion below.
integer (incl. byte, short, int, long,
%x Hex string.
bigint)

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.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios,
where we need to use the wrapper classes.
 Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
 Serialization: We need to convert the objects into streams to perform the serialization.
If we have a primitive value, we can convert it in objects through the wrapper classes.
 Synchronization: Java synchronization works with objects in Multithreading.

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


 java.util package: The java.util package provides the utility classes to deal with
objects.
 Collection Framework: Java collection framework works with objects only. All classes
of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

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.

Wrapper class Example: Primitive to Wrapper


//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a)
internally
System.out.println(a+" "+i+" "+j);
}
}

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.

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}

Wrapper class Example: String to Integer

public class WrapperExample3{


public static void main(String args[]){
int num = 7;
System.out.println("The Value of 'num' is "+num);
Integer num1 = num;
System.out.println("The Value of 'num1' is "+num1);
int num2 = num1;
System.out.println("The Value of 'num2' is "+num2);
String num3 = "15";
System.out.println("The Value of 'num3' is "+num3);
int num4 = Integer.parseInt(num3);
//System.out.println("The Value of 'num2*num3' is "+num2*num3);
System.out.println("The Value of 'num2*num4' is "+num2*num4);
}
}

6. Programming Exercises (PE)

PE 2.1 – Java program to Check whether an alphabet is vowel or consonant

public class VowelConsonant {

public static void main(String[] args) {

char ch = 'j';

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'


)
System.out.println(ch + " is vowel");
else
System.out.println(ch + " is consonant");

}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.2 – Java program to Check whether a number is even or odd

import java.util.Scanner;
public class EvenOdd1 {
public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

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;

public class EvenOdd2 {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

String evenOdd = (num % 2 == 0) ? "even" : "odd";

System.out.println(num + " is " + evenOdd);

}
}

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;

// checks if number is greater than 0

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


if (number > 0) {
System.out.println("The number is positive.");
}

// checks if number is less than 0


else if (number < 0) {
System.out.println("The number is negative.");
}

// if both condition is false


else {
System.out.println("The number is 0.");
}
}
}

PE 2.5 – Java program to print Multiplication Table (using Format Specifier)

public class MultiplicationTable {

public static void main(String[] args) {

int num = 5;
for(int i = 1; i <= 10; ++i)
{
System.out.printf("%d x %d = %d \n", num, i, num * i);
}
}
}

PE 2.6 – Java program to print Fibonacci Series


class Fib{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)
//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.7 – Java program to check whether the given number is prime or not
public class PrimeNumber {

public static void main(String[] args) {

int num = 29;


boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}

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");
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.9 – Java program to print the length of the given String

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)+"'.");
}
}

PE 2.11 – Java program to print the factorial of the given number

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");

int number = myObj.nextInt();

for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.12 – Java program to print the largest of three numbers using Ternary Operator

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 + " ");
}
}
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.14 – Java program to print the Factors of the given Negative Number

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.15 – Java program to use Switch Case

public class SwitchExample {


public static void main(String[] args) {
//Declaring a variable for switch expression
int number=56;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("Number is 10");
break;
case 20: System.out.println("Number is 20");
break;
case 30: System.out.println("Number is 30");
break;
//Default case statement
default:System.out.println("Number is not 10, 20 or 30");
break;
}
}
}

PE 2.16 – Java program to print month name for the given number using Switch Case

public class SwitchMonthExample {


public static void main(String[] args) {
int month=5;
String monthString="";
switch(month){
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
System.out.println(monthString);
}
}

PE 2.17 – Java program to check and print check Vowel or Consonant using Switch Case

public class SwitchVowelExample {


public static void main(String[] args) {
char ch='O';
switch(ch)
{
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
case 'A':
System.out.println("Vowel");
break;
case 'E':
All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).
System.out.println("Vowel");
break;
case 'I':
System.out.println("Vowel");
break;
case 'O':
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}

PE 2.18 – Java program to use Switch Case with loops

public class SwitchLoop {

public static void main(String[] args) {

for(int i=0; i<=10; i++) {


switch(i){
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i value is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i value is less than 10");
break;

default:
System.out.println("Default statement");

}
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.19 – Java program to use Nested Switch Case

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();

// Outer Switch starts here


switch (a) {
// Condition a = 1
case 1:

// Inner Switch starts here


switch (b) {
// Condition b = 1
case 1:
System.out.println("b is 1");
break;

// 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;
}

}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.20 – Java program to print Reverse Numbers using Do While

class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}

PE 2.21 – Java program to print Sum of Positive Numbers

import java.util.Scanner;

class DWexample {
public static void main(String[] args) {

int sum = 0;
int number = 0;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// do...while loop continues until entered number is positive


do {
// add only positive numbers
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
} while(number >= 0);

System.out.println("Sum = " + sum);


input.close();
}
}

PE 2.22 – Java program to print Multiplication table using Do While loop

import java.util.*;

public class Main{


public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int n=sc.nextInt();
int i=1;
System.out.println("The multiplication table of "+n+" is:
");
do

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


{
System.out.println(n+" * "+i+" = "+ (n*i));
i++;
}while(i<=10);
}
}

PE 2.23 – Java program to print Multiplication table using Nested Do While loop

public class Mtablerxc {


public static void main(String[] args)
{
int row, column;
System.out.println("Multiplication Table 1-5 \n");
row = 1; // Initialization.
do {
column = 1;
do{
int x = row * column;
System.out.print(" "+ x);
column = column + 1;
}while(column <= 5);
System.out.println("\n");
row = row + 1;
} while(row <= 5);
}
}

PE 2.24 – Java program to generate Random Number using Do While loop

// Import the Random class


import java.util.Random;
import java.util.Scanner;
public class RandExampleDW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a random object
Random rand = new Random();
System.out.println("Enter an integer between 0-9");
int num = input.nextInt();
// Random integer between 0 - 9
int randomNum = rand.nextInt(10);
do{
// Generate a new random number
randomNum = rand.nextInt(10);
System.out.println("User: " + num + " : " + "Random
number: " + randomNum);
// As long input is different from random number
} while (num != randomNum);
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.25 – Java program to collect and print Name and Department of the Candidates using
Arrays

import java.util.*;
class ArrayExample {
public static void main(String[] args) {
Scanner xx = new Scanner(System.in);

String[] name = new String [5];


String[] department = new String [5];

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]+"'.");
}
}
}

PE 2.26 – Java program to print Power and Square Root of a Number

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);
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


PE 2.27 – Java program to total the value of elements in the given array using enhanced-for
loop

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) {

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

System.out.println("The below given output is printed using For


Loop.");

// iterating through an array using a for loop


for (int i = 0; i < vowels.length; ++ i) {
System.out.println(vowels[i]);
}

System.out.println("The below given output is printed using For-


each Loop.");

for (char item: vowels) {


System.out.println(item);
}
}
}

PE 2.29 – Java program to create, convert and print Strings

public class StringExample{


public static void main(String args[]){
//creating string by Java string literal
String s1="VIT";
char ch[]={'U','n','i','v','e','r','s','i','t','y'};
//converting char array to string
String s2=new String(ch);
//creating Java string by new keyword
String s3=new String("SENSE School");

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).


System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

All Rights Reserved. Contact Dr. Logesh on Telegram (https://t.me/DrLogesh).

You might also like