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

The If Statement: I. If Definition

The document discusses various Java control flow statements including if, if-else, if-else-if, switch statements and loops. It provides definitions and syntax for each statement, along with examples of programs using them. If statements execute code based on boolean conditions. If-else and if-else-if allow for multiple conditions. Switch statements check a variable against case values. Loops repeat code for a set number of iterations or until a condition is met. Function overloading and constructors are also covered.

Uploaded by

Avishkar Gosavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

The If Statement: I. If Definition

The document discusses various Java control flow statements including if, if-else, if-else-if, switch statements and loops. It provides definitions and syntax for each statement, along with examples of programs using them. If statements execute code based on boolean conditions. If-else and if-else-if allow for multiple conditions. Switch statements check a variable against case values. Loops repeat code for a set number of iterations or until a condition is met. Function overloading and constructors are also covered.

Uploaded by

Avishkar Gosavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

THE IF STATEMENT :

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

In programming languages, loops are used to execute a set of instructions/functions


repeatedly when some conditions become true. There are three types of loops in Java.

o for loop
o while loop
o do-while loop

Program no. 3

Using switch statement, write a menu driven program to:

(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

For an incorrect choice, an appropriate error message should be displayed.

Input:

import java.util.Scanner;

public class Calculate {

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("1. Factors of number");

System.out.println("2. Factorial of number");

System.out.print("Enter your choice: ");

int choice = in.nextInt();

Page 6 of 27
int num;

switch (choice) {

case 1:

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

num = in.nextInt();

for (int i = 1; i < num; i++) {

if (num % i == 0) {

System.out.print(i + " ");

System.out.println();

break;

case 2:

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

num = in.nextInt();

int f = 1;

for (int i = 1; i <= num; i++)

f *= i;

System.out.println("Factorial = " + f);

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:

(a) To print the Floyd's triangle:


1
2   3
4   5   6
7   8   9   10
11 12 13 14 15

(b) To display the following pattern:


I
IC
ICS
ICSE

For an incorrect option, an appropriate error message should be displayed.

Input:

import java.util.Scanner;

public class KboatPattern {

public void choosePattern() {

Scanner in = new Scanner(System.in);

System.out.println("Type 1 for Floyd's triangle");

System.out.println("Type 2 for an ICSE pattern");

System.out.print("Enter your choice: ");

int ch = in.nextInt();

switch (ch) {

case 1:

int a = 1;

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(a++ + "\t");

Page 9 of 27
}

System.out.println();

break;

case 2:

String s = "ICSE";

for (int i = 0; i < s.length(); i++) {

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

System.out.print(s.charAt(j) + " ");

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

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={'j','a','v','a','t','p','o','i','n','t'};  
String s=new String(ch);  

is same as:

String s="javatpoint";  

Method Prototype Description


char charAt(int index) Returns the character at the specified
index.
int capacity( )
Returns maximum no. of characters that
can be entered in the current string
int compareTo(String1, object(this) i.e., its capacity.
anotherString)
Compares two strings lexicographically1.
String concat(String str)
Concatenates the specified string to the
end of this string (current String object )
string.
str1 + str2
Concatenation operator (i.e., + ), achieves
same as concat method.
boolean endswith ( String str)
Tests if the this string ( current String
boolean equals ( Strings str ) object ) ends with the specified suffix ( str ).

Compares the this string ( current String


boolean equalsIgnoreCase object ) to the specified object str.
(String str )
Compares the this string ( current String
int indexOf ( char ch ) object ) to str , ignoring case
considerations.

Returns the index2 within the this string


int lastIndexOf ( char ch ) ( current String object ) of the first
occurrence of the specified character.

Returns the index within the this string of


int length ( )
the last occurrence of the specified
character.

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

Returns a new string that is a substring o the


String substring ( int
this string.
beginIndex , int endIndex )

Converts all of the characters in the this String


String toLowerCase ( ) to lower case.

String toString ( ) Returns the string itself.

String toUpperCase ( ) Converts all of the characters in the this String


to upper case.

String trim ( ) Removes white space from both ends of the


this String.

String valueOf ( all types) Returns string representation of the passed


argument e.g., 12 represented as “12”

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:

public class Ar1 {

public int marks[];

Ar1() {

marks=new int[5];

public void calcResult(int arr[]) {

marks=arr;

int total=0,i;

float average=0;

for(i=0;i<5;i++) {

total+=marks[i];

average=total/5;

System.out.println("Marks in 5 subjects are :");

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

System.out.println("Average marks are :"+average);

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

Search an element in an array using linear Search. Pass the element to be


searched for, as an argument.

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

Sort an Array using Bubble Sort. Pass array as Argument.

Input:

class ArraySorting {

public static void bubbleSort(int A[]) {

//array elements are : {5,3,8,4,9,2,1,12,90,15}

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
}

System.out.println("Array in ascending order is

-->");

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

Program to determine whether the given number is a Special Number or not.

Input:

import java.util.Scanner;

public class SpecialNumberExample1 {

public static void main(String args[]) {

int num, number, last_digit, sum_Of_Fact = 0;

Scanner sc = new Scanner(System.in);

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

number = sc.nextInt();

num = number;

while (number > 0) {

last_digit = number % 10;

int fact=1;

for(int i=1; i<=last_digit; i++) {

fact=fact*i;

Page 25 of 27
sum_Of_Fact = sum_Of_Fact + fact;

number = number / 10;

if(num==sum_Of_Fact) {

System.out.println(num+ " is a special number.");

else {

System.out.println(num+ " is not a special number.");

Output:

Page 26 of 27
BIBLIOGRAPHY

 ICSE solved papers last10 years.

 Computer Applications text book(Dhanpat Rai & Co.)

 www.google.com

www.javapoint.com

www.geeksforgeeks.org

Page 27 of 27

You might also like