The If Statement: I. If Definition
The If Statement: I. If Definition
i. if
Definition :
An if statement tests a particular condition; if the condition evaluates to true, a
course-ofaction is followed i.e, a statement or set-of-statements is executed.
Otherwise (if the condition evaluates to false), the course-of-action is ignored.
Syntax:
if(expression)
statement;
ii.if else
Definition :
Another form of if that allows for this kind of either-or condition by providing an else
clause is known as if-else statement.The if-else statement tests an expression and
depending upon its truth value one of the two sets-of-action is executed.
Syntax:
if(expression)
statement 1;
else
statement 2;
iii.if-else-if:
A common programming construct in Java is the if-else-if ladder, which is often also
called the if-else-if staircase because of its appearance.
Syntax:
if(expression1)
statement 1;
else if(expression2)
statement 2;
else if(expression 3)
statement 3;
:
:
else statement n;
Page 1 of 27
Program no. 1
Write a program to check whether the given integer is positive negative or zero.
Input:
import java.util.Scanner;
public class TriangleTest {
public static Boolean CanMake(double a1, double a2, double a3) {
boolean result;
if(a1+a2+a3==180)
result=true;
else
result=false;
return result;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double angle1, angle2, angle3;
System.out.println("Enter 3 angles");
System.out.print("Angle1 :");
angle1=sc.nextInt();
System.out.print("Angle2 :");
angle2=sc.nextInt();
System.out.print("Angle3 :");
angle3=sc.nextInt();
if(CanMake(angle1, angle2, angle3)==true) {
if(angle1>90||angle2>90||angle3>90)
System.out.println("Given 3 angles make an Obtuse triangle");
else if(angle1<90 && angle2<90 && angle3<90)
System.out.println("Given 3 angles make an Acute triangle");
else if(angle1==90||angle2==90||angle3==90)
System.out.println("Given 3 angles make Right-angled triangle");
}
else
Page 2 of 27
System.out.println("Given 3 angles CANNOT make a triangle");
}
}
Output:
Page 3 of 27
Switch Statement
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for
each case.
Syntax:
switch(expression)
{
case constant1:statement-sequence1;
break;
case constant2:statement-sequence2;
break;
case constant3:statement-sequence3;
break;
case constantn-1:statement-sequencen-1;
break;
[default: statement-sequencen];
}
Page 4 of 27
Program no. 2
Program to input number of week’s day (1-7) and translate to its equivalent
name of the week (e.g. 1 to Sunday, 2 to Monday,…., 7 to Saturday)
Input:
public class Days {
public void Weekday(int dow) {
String ans;
switch (dow) {
case 1: ans = “Sunday”; break ;
case 2: ans = “Monday”; break ;
case 3: ans = “Tuesday”; break ;
case 4: ans = “Wednesday”; break ;
case 5: ans = “Thursday”; break ;
case 6: ans = “Friday”; break ;
case 7: ans = “Saturday”; break ;
default:ans =”Wrong Day Number”;
}
System.out.println(“Day no.”+dow+”is”+ans);
}
}
Output:
Page 5 of 27
Loops
o for loop
o while loop
o do-while loop
Program no. 3
(a) find and display all the factors of a number input by the user ( including 1
and the excluding the number itself).
Example:
Sample Input : n = 15
Sample Output : 1, 3, 5
(b) find and display the factorial of a number input by the user (the factorial of a
non-negative integer n, denoted by n!, is the product of all integers less than or
equal to n.)
Example:
Sample Input : n = 5
Sample Output : 5! = 1*2*3*4*5 = 120
Input:
import java.util.Scanner;
Page 6 of 27
int num;
switch (choice) {
case 1:
num = in.nextInt();
if (num % i == 0) {
System.out.println();
break;
case 2:
num = in.nextInt();
int f = 1;
f *= i;
break;
default:
System.out.println("Incorrect Choice");
break;
Page 7 of 27
}
Output:
Page 8 of 27
Program no. 4
Using the switch statement, write a menu driven program for the following:
Input:
import java.util.Scanner;
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 1;
System.out.print(a++ + "\t");
Page 9 of 27
}
System.out.println();
break;
case 2:
String s = "ICSE";
System.out.println();
break;
default:
System.out.println("Incorrect Choice");
Output:
Page 10 of 27
Page 11 of 27
Function Overloading
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading. If we have to perform only one operation, having
same name of the methods increases the readability of the program.
Program no.5
Program to calculate the volume of rectangular box, cube and cylinder using
function overloading.
Input:
class Overload {
double area(float l, float w, float h) {
return l * w * h;
}
double area(float l) {
return l * l * l;
}
double area(float r, float h) {
return 3.1416 * r * r * h;
}
}
public class MethodOverloading {
public static void main(String args[]) {
Overload overload = new Overload();
double rectangleBox = overload.area(5, 8, 9);
System.out.println("Area of ractangular box is " + rectangleBox);
System.out.println("");
Page 12 of 27
double cube = overload.area(5);
System.out.println("Area of cube is " + cube);
System.out.println("");
double cylinder = overload.area(6, 12);
System.out.println("Area of cylinder is " + cylinder);
}
}
Output:
Page 13 of 27
Constructors
A constructor in Java is similar to a method that is invoked when an object of the
class is created. Unlike Java methods, a constructor has the same name as that of the
class and does not have any return type.
Types of Constructors:
i.Parameterized Constructors- A constructor is called Parameterized
Constructor when it accepts a specific number of parameters.
ii.Non-parameterized Constructors- A constructor that has no parameter is known
as the default constructor.
Program No. 6
Program that implements a temperature lass that stores a temperature in
Fahrenheit and provides functionality to convert the temperature to Celsius also
using Parameterized Constructor.
Input:
class Temperature {
double temp;
public Temperature() { //parameter less default constructor
temp=92; //default temperature given is 92° Fahrenheit
}
public Temperature(double t) { //parameterized constructor
temp=t;
}
public double convert2Celsius() {
double Cel=(5.0/9)*(temp-32);
return Cel;
}
public double getTemp() {
return temp;
}
}
public class ImplementTemperature {
public static void main(String[]args) {
Page 14 of 27
Temperature dayTemp=new Temperature(94);
System.out.println("Temperature in Fahrenheit is:"
+dayTemp.getTemp());
System.out.println("Temperature in Celsius is:"
+dayTemp.convert2Celsius());
Temperature dTemp=new Temperature();
System.out.println("Other temperature in Fahrenheit is:"
+dTemp.getTemp());
System.out.println("Other temperature in Celsius is:"
+dTemp.convert2Celsius());
} //end main
} //end class
Output:
Page 15 of 27
String
Char ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
String replace ( char oldChar , Returns the length of the this string.
Page 16 of 27
char newChar) Returns a new string resulting from replacing
all occurrences of oldChar in the this string
with newChar.
boolean startsWith (String str ) Tests if the this string starts with the specified
suffix (str ).
Page 17 of 27
Program no. 7
Program to accept a string in lower case and change the first letter of every word
to upper case. Display the new string.
Input:
import java.util.Scanner;
public class StrManip {
public static void main(String[]args) {
Scanner inp=new Scanner(System.in);
System.out.print("Enter a string in lower case :");
String st=inp.nextLine();
StringBuffer str=new StringBuffer(st);
int ln=str.length();
char ch;
if(str.charAt(0)!=' ') {
ch=str.charAt(0);
str.setCharAt(0,Character.toUpperCase(ch));
}
for(int i=0;i<ln-1;i++)
if(str.charAt(i)==' '&& str.charAt(i+1)!=' ') {
ch=str.charAt(i+1);
str.setCharAt((i+1),Character.toUpperCase(ch));
}
System.out.println(str);
}
}
Output:
Page 18 of 27
Program no.8
Program to input a string and print out the text with the uppercase and
lowercase letters reversed, but all other characters should remain the same as
before.
Input:
import java.io.*;
public class TheString {
public static void main(String[]args) throws IOException {
BufferedReader kb=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter string");
String str=kb.readLine();
StringBuffer nstr=new StringBuffer(str);
Character ch1=' ';
for(int i=0;i<str.length();i++) {
ch1=nstr.charAt(i);
if(ch1.isUpperCase(ch1))
nstr.setCharAt(i,ch1.toLowerCase(ch1));
else
nstr.setCharAt(i,ch1.toUpperCase(ch1));
}
System.out.println(nstr);
}
}
Output:
Page 19 of 27
Arrays
i.Normal Array
Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Program no. 9
Program to read marks of 5 subjects of a student and store them under an array
namely marks. Calculate the total and average marks of the Student.
Input:
Ar1() {
marks=new int[5];
marks=arr;
int total=0,i;
float average=0;
for(i=0;i<5;i++) {
total+=marks[i];
average=total/5;
for(i=0;i<5;i++) {
System.out.print(marks[i]+",");
System.out.println();
Page 20 of 27
System.out.println("Total marks are :"+total);
Output:
ii.Searching:
Sometimes you need to search for an element in an array. To accomplish this task ,
you can use different searching techniques. It consists of two very common search
techniques viz ., linear search and binary search.
Linear Search:
Linear search refers to the searching technique in which each element of an array is
compared with the search item, one by one, until the search – item is found or all elements
have been compared.
Binary Search:
Binary Search is a search technique that works for sorted arrays. Here search item is
compared with the middle element of the array. If the search- item matches with the
element , search finishes.If the search – item is less than the middle perform (in ascending
order) perform binary search in the first half of the array , otherwise perform binary search
in the latter half of the array.
Page 21 of 27
Program no. 10
Input:
class Linear {
public void lSearch(int n) {
int A[]={5,3,8,4,9,2,1,12,90,15};
int flag=0,i;
for(i=0;i<10;i++) {
if(n==A[i]) {
flag=1;
break;
}
}
if(flag==1)
System.out.println("Element present at position"+(i+1));
else
System.out.println("Element not present");
}
}
Output:
Page 22 of 27
iii.Sorting:
Sorting of an array means arranging the array elements in a specified order i.e.,
either ascending or descending order. There are several sorting techniques available e.g.,
shell sort, shuttle sort, bubble sort, selection sort, quick sort, heap sort, etc. But the most
popular techniques are selection sort and bubble sort.
Selection Sort
Selection sort is a sorting technique where next smallest (or next largest) element is
found in the array and moved to its correct position e.g., the smallest element should be at
1st position (for ascending array), second smallest should be at 2 nd position and so on.
Bubble Sort
The idea of bubble sort is to move the largest element to the highest index position
in the array. To attain this, two adjacent elements are compared repeatedly and exchanged
if they are not in the correct order.
Program no. 11
Input:
class ArraySorting {
int i,j,tmp;
for(i=0;i<10;i++)
for(j=0;j<9-i;j++) {
if(A[j]>A[j+1]) {
tmp=A[j];
A[j]=A[j+1];
A[j+1]=tmp;
Page 23 of 27
}
-->");
for(i=0;i<10;i++)
System.out.println(A[i]+"\n");
Output:
Page 24 of 27
Special Number in Java
If the sum of the factorial of digits of a number (N) is equal to the number itself, the
number (N) is called a special number.
N=145
Sum=1!+4!+5!
=1+24+120
=140
∴N==sum
Program no. 12
Input:
import java.util.Scanner;
number = sc.nextInt();
num = number;
int fact=1;
fact=fact*i;
Page 25 of 27
sum_Of_Fact = sum_Of_Fact + fact;
if(num==sum_Of_Fact) {
else {
Output:
Page 26 of 27
BIBLIOGRAPHY
www.google.com
www.javapoint.com
www.geeksforgeeks.org
Page 27 of 27