You are on page 1of 12

import java.util.

Scanner;

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Output 1:

Enter an Integer number:


78
Entered number is even
Output 2:

Enter an Integer number:


77
Entered number is odd

public class JavaExample {

public static void main(String[] args) {


double[] arr = {19, 12.89, 16.5, 200, 13.7};
double total = 0;

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


total = total + arr[i];
}

/* arr.length returns the number of elements


* present in the array
*/
double average = total / arr.length;

/* This is used for displaying the formatted output


* if you give %.4f then the output would have 4 digits
* after decimal point.
*/
System.out.format("The average is: %.3f", average);
}
}
Output:

The average is: 52.418

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {


System.out.println("How many numbers you want to enter?");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
/* Declaring array of n elements, the value
* of n is provided by the user
*/
double[] arr = new double[n];
double total = 0;

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


System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = scanner.nextDouble();
}
scanner.close();
for(int i=0; i<arr.length; i++){
total = total + arr[i];
}

double average = total / arr.length;

System.out.format("The average is: %.3f", average);


}
}
Output:

How many numbers you want to enter?


5
Enter Element No.1: 12.7
Enter Element No.2: 18.9
Enter Element No.3: 20
Enter Element No.4: 13.923
Enter Element No.5: 15.6
The average is: 16.225
public class JavaExample {

public static void main(String[] args) {

int num = 370, number, temp, total = 0;

number = num;
while (number != 0)
{
temp = number % 10;
total = total + temp*temp*temp;
number /= 10;
}

if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output:

370 is an Armstrong number

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

int num, number, temp, total = 0;


System.out.println("Ënter 3 Digit Number");
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
scanner.close();
number = num;

for( ;number!=0;number /= 10)


{
temp = number % 10;
total = total + temp*temp*temp;
}

if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output:

Ënter 3 Digit Number


371
371 is an Armstrong number

class SumOfArray{
public static void main(String args[]){
int[] array = {10, 20, 30, 40, 50, 10};
int sum = 0;
//Advanced for loop
for( int num : array) {
sum = sum+num;
}
System.out.println("Sum of array elements is:"+sum);
}
}
Output:

Sum of array elements is:160

import java.util.Scanner;
class SumDemo{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
int sum = 0;
System.out.println("Enter the elements:");
for (int i=0; i<10; i++)
{
array[i] = scanner.nextInt();
}
for( int num : array) {
sum = sum+num;
}
System.out.println("Sum of array elements is:"+sum);
}
}
Output:

Enter the elements:


1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55

public class JavaExample {


public static void main(String[] args) {

//We will find the factorial of this number


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

Factorial of 5 is: 120

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Enter the number:


6
Factorial of 6 is: 720

Java String Methods

 Java String length(): The Java String length() method tells the length of the
string. It returns count of total number of characters present in the String.
For example:
1
public class Example{
2 public static void main(String args[]{
3 String s1="hello";
4 String s2="whatsup";
5 System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
6 }}
7
Here, String length() function will return the length 5 for s1 and 7 for s2 respectively.

 Java String compareTo(): The Java String compareTo() method compares the
given string with current string. It is a method of ‘Comparable’ interface which is
implemented by String class. Don’t worry, we will be learning about String
interfaces later. It either returns positive number, negative number or 0. For
example:

1
2 public class CompareToExample{
public static void main(String args[]){
3 String s1="hello";
4 String s2="hello";
5 String s3="hemlo";
6 String s4="flag";
7 System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m"
8 System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
9 }}
10
This program shows the comparison between the various string. It is noticed that
if s1 > s2, it returns a positive number
if s1 < s2, it returns a negative number
if s1 == s2, it returns 0

 Java String concat() : The Java String concat() method combines a specific
string at the end of another string and ultimately returns a combined string. It is
like appending another string. For example:

1 public class ConcatExample{


2 public static void main(String args[]){
3 String s1="hello";
4 s1=s1.concat("how are you");
5 System.out.println(s1);
}}
6
 The above code returns “hellohow are you”.
 Java String IsEmpty() : This method checks whether the String contains
anything or not. If the java String is Empty, it returns true else false. For example:
1
public class IsEmptyExample{
2 public static void main(String args[]){
3 String s1="";
4 String s2="hello";
5 System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
6 }}
7

 Java String Trim() : The java string trim() method removes the leading and
trailing spaces. It checks the unicode value of space character (‘\u0020’) before
and after the string. If it exists, then removes the spaces and return the omitted
string. For example:

1 public class StringTrimExample{


2 public static void main(String args[]){
3 String s1=" hello ";
4 System.out.println(s1+"how are you"); // without trim()
5 System.out.println(s1.trim()+"how are you"); // with trim()
}}
6
 In the above code, the first print statement will print “hello how are you” while the
second statement will print “hellohow are you” using the trim() function.
 Java String toLowerCase() : The java string toLowerCase() method converts
all the characters of the String to lower case. For example:

1 public class StringLowerExample{


2 public static void main(String args[]){
3 String s1="HELLO HOW Are You?”;
4 String s1lower=s1.toLowerCase();
5 System.out.println(s1lower);}
}
6
 The above code will return “hello how are you”.
 Java String toUpper() : The Java String toUpperCase() method converts all the
characters of the String to upper case. For example:

1 public class StringUpperExample{


2 public static void main(String args[]){
3 String s1="hello how are you";
4 String s1upper=s1.toUpperCase();
5 System.out.println(s1upper);
}}
6
 The above code will return “HELLO HOW ARE YOU”.

 Java String ValueOf(): This method converts different types of values into
string.Using this method, you can convert int to string, long to string, Boolean to
string, character to string, float to string, double to string, object to string and
char array to string. The signature or syntax of string valueOf() method is given
below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

Let’s understand this with a programmatic example:


1 public class StringValueOfExample{
2 public static void main(String args[]){
3 int value=20;
4 String s1=String.valueOf(value);
5 System.out.println(s1+17); //concatenating string with 10
}}
6
In the above code, it concatenates the Java String and gives the output – 2017.
 Java String replace(): The Java String replace() method returns a string,
replacing all the old characters or CharSequence to new characters. There are 2
ways to replace methods in a Java String.
1 public class ReplaceExample1{
2 public static void main(String args[]){
3 String s1="hello how are you";
4 String replaceString=s1.replace('h','t');
System.out.println(replaceString); }}
5
 In the above code, it will replace all the occurrences of ‘h’ to ‘t’. Output to the
above code will be “tello tow are you”. Let’s see the another type of using replace
method in java string:

Java String replace(CharSequence target, CharSequence replacement)


method :

1 public class ReplaceExample2{


2 public static void main(String args[]){
3 String s1="Hey, welcome to Edureka";
4 String replaceString=s1.replace("Edureka","Brainforce");
5 System.out.println(replaceString);
}}
6
 In the above code, it will replace all occurrences of “Edureka” to “Brainforce”.
Therefore, the output would be “ Hey, welcome to Brainforce”.
 Java String contains() :The java string contains() method searches the
sequence of characters in the string. If the sequences of characters are found,
then it returns true otherwise returns false. For example:
1
class ContainsExample{
2 public static void main(String args[]){
3 String name=" hello how are you doing?";
4 System.out.println(name.contains("how are you")); // returns true
5 System.out.println(name.contains("hello")); // returns true
System.out.println(name.contains("fine")); // returns false
6 }}
7
 In the above code, the first two statements will return true as it matches the String
whereas the second print statement will return false because the characters are
not present in the string.
 Java String equals() : The Java String equals() method compares the two given
strings on the basis of content of the string i.e Java String representation. If all
the characters are matched, it returns true else it will return false. For example:

1
2 public class EqualsExample{
public static void main(String args[]){
3 String s1="hello";
4 String s2="hello";
5 String s3="hi";
6 System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
7 }
8 }
9
Learn Java From Experts

 Java String equalsIgnoreCase(): This method compares two string on the


basis of content but it does not check the case like equals() method. In this
method, if the characters match, it returns true else false. For example:

1
public class EqualsIgnoreCaseExample{
2 public static void main(String args[]){
3 String s1="hello";
4 String s2="HELLO";
5 String s3="hi";
6 System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
7 }}
8
 In the above code, the first statement will return true because the content is same
irrespective of the case. Then, in the second print statement will return false as
the content doesn’t match in the respective strings.
 Java String toCharArray(): This method converts the string into a character
array i.e first it will calculate the length of the given Java String including spaces
and then create an array of char type with the same content. For example:

1 StringToCharArrayExample{
2 public static void main(String args[]){
3 String s1="Welcome to Edureka";
4 char[] ch=s1.toCharArray();
5 for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
6 }}}
7
 The above code will return “Welcome to Edureka”.
 Java StringGetBytes() : The Java string getBytes() method returns the
sequence of bytes or you can say the byte array of the string. For example:

1
public class StringGetBytesExample {
2 public static void main(String args[]){
3 String s1="ABC";
4 byte[] b=s1.getBytes();
5 for(int i=0;i<b.length;i++){
6 System.out.println(b[i]);
}
7 }}
8
 In the above code, it will return the value 65,66,67.

 Java String IsEmpty() : This method checks whether the String is empty or not.
If the length of the String is 0, it returns true else false. For example:

1
public class IsEmptyExample{
2 public static void main(String args[]) {
3 String s1="";
4 String s2="hello";
5 System.out.prinltn(s1.isEmpty()); // returns true
System.out.prinltn(s2.isEmpty()); // returns false
6 }}
7
In the above code, the first print statement will return true as it does not contain anything
while the second print statement will return false.

 Java String endsWith() : The Java String endsWith() method checks if this
string ends with the given suffix. If it returns with the given suffix, it will return
true else returns false. For example:

1
public class EndsWithExample{
2 public static void main(String args[]) {
3 String s1="hello how are you”;
4 System.out.println(s1.endsWith("u")); // returns true
5 System.out.println(s1.endsWith("you")); // returns true
System.out.println(s1.endsWith("how")); // returns false
6 }}
7
Write a program to implement all string operations.
import java.util.*;
class StringOperation
{
public static void main(String[] args)
{
String first="",second="";
Scanner sc=new Scanner(System.in);
System.out.println("String Operation");
System.out.println();
System.out.print("Enter the first Sting: ");
first=sc.nextLine();
System.out.print("Enter the second Sting: ");
second=sc.nextLine();
System.out.println("The strings are: "+first+" , "+second);
System.out.println("The length of the first string is :"+first.length());
System.out.println("The length of the second string is :"+second.length());
System.out.println("The concatenation of first and second string is :"+first.concat("
"+second));
System.out.println("The first character of " +first+" is: "+first.charAt(0));
System.out.println("The uppercase of " +first+" is: "+first.toUpperCase());
System.out.println("The lowercase of " +first+" is: "+first.toLowerCase());
System.out.print("Enter the occurance of a character in "+first+" : ");
String str=sc.next();
char c=str.charAt(0);
System.out.println("The "+c+" occurs at position " + first.indexOf(c)+ " in " + first);
System.out.println("The substring of "+first+" starting from index 3 and ending at 6 is: "
+ first.substring(3,7));
System.out.println("Replacing 'a' with 'o' in "+first+" is: "+first.replace('a','o'));
boolean check=first.equals(second);
if(!check)
System.out.println(first + " and " + second + " are not same.");
else
System.out.println(first + " and " + second + " are same.");
}
}

Output

C:\Users\Jaisha\Desktop\Java>javac StringOperation.java

C:\Users\Jaisha\Desktop\Java>java StringOperation
String Operation

Enter the first Sting: The World is Beautiful.


Enter the second Sting: Learn to enjoy every moment.
The strings are: The World is Beautiful. , Learn to enjoy every moment.
The length of the first string is :23
The length of the second string is :28
The concatenation of first and second string is :The World is Beautiful. Learn to enjoy every
moment.
The first character of The World is Beautiful. is: T
The uppercase of The World is Beautiful. is: THE WORLD IS BEAUTIFUL.
The lowercase of The World is Beautiful. is: the world is beautiful.
Enter the occurance of a character in The World is Beautiful. : e
The e occurs at position 2 in The World is Beautiful.
The substring of The World is Beautiful. starting from index 3 and ending at 6 is: Wor
Replacing 'a' with 'o' in The World is Beautiful. is: The World is Beoutiful.
The World is Beautiful. and Learn to enjoy every moment. are not same.

You might also like