[Go to site: main page, start]

0% found this document useful (0 votes)
31 views10 pages

Floyd's Triangle in Java Program

The document provides 24 code examples demonstrating various Java programming concepts and interview questions. The examples cover topics such as printing Floyd's triangle, finding substrings in a string, reversing a string, checking for palindromes, adding and multiplying matrices, getting the transpose of a matrix, comparing strings, checking if a string ends with a character/text, using the indexOf() method, replacing parts of a string, splitting a string, removing spaces from a string, converting case, creating and calling methods, finding string length, concatenating strings, replacing parts of a string, using static blocks, explaining static vs instance methods, creating multiple classes, using constructors, constructor overloading, exception handling, and throwing custom exceptions.

Uploaded by

Kavitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views10 pages

Floyd's Triangle in Java Program

The document provides 24 code examples demonstrating various Java programming concepts and interview questions. The examples cover topics such as printing Floyd's triangle, finding substrings in a string, reversing a string, checking for palindromes, adding and multiplying matrices, getting the transpose of a matrix, comparing strings, checking if a string ends with a character/text, using the indexOf() method, replacing parts of a string, splitting a string, removing spaces from a string, converting case, creating and calling methods, finding string length, concatenating strings, replacing parts of a string, using static blocks, explaining static vs instance methods, creating multiple classes, using constructors, constructor overloading, exception handling, and throwing custom exceptions.

Uploaded by

Kavitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java for Testers – Interview Questions and Answers Part-2

1)  Write a Java program to print Floyd’s triangle?


public class FloydTriangle {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of rows");
int rows = [Link]();
printFloydTriangle(rows);
}
public static void printFloydTriangle(int n){
int number = 1;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
[Link](number +" ");
number++;
}
[Link]();
}
}
}
2) Write a Java program to find all the sub-string of given string?
public class FindSubString {
public static void main(String[] args) {
String name = "Selenium And Java Interview Questions";
[Link]([Link]("Java")); // true
[Link]([Link]("java")); // false
[Link]([Link]("Interview")); // true
[Link]([Link]("questions")); // false
}
}
3) Write a Java program to print the given string in reverse?
public class ReverseString {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Enter input string");
String s1 = [Link]();
String s2 = reverseString(s1);
[Link]("Reversed String is: "+s2);
}
public static String reverseString(String s){
String rev="";
char[] arr = [Link]();
for(int i=[Link]-1;i>=0;i--)
rev = rev + arr[i];
return rev;
}
}
4) Write a Java program to check whether the given number is palindrome?
public class PalindromeNumber {
public static void main(String[] args){
int r,sum=0,temp;
Scanner sc = new Scanner([Link]);
[Link]("Enter a number");
int n = [Link]();
temp=n;
while (n > 0) {
r = n%10;
sum = (sum*10) + r;
n=n/10;
}
if(temp==sum)
[Link]("Number is palindrome");
else
[Link]("Number is not palindrome");
}
}
5) Write a Java program to add two matrix?
public class AddTwoMatrix {
public static void main(String args[]) {
//creating two matrices
int a[][] = {{1, 3, 4}, {2, 4, 3}, {3, 4, 5}};
int b[][] = {{1, 3, 4}, {2, 4, 3}, {1, 2, 4}};
//creating another matrix to store the sum of two matrices
int c[][] = new int[3][3];
//adding and printing addition of 2 matrices
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
[Link](c[i][j] + " ");
}
[Link]();
}
}
}
6) Write a Java program to multiply two matrix?
public class MultiplyTwoMatrix {
public static void main(String args[]) {
//creating two matrices
int a[][] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
int b[][] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
//creating another matrix to store the multiplication of two matrices
int c[][] = new int[3][3];
//multiplying and printing multiplication of 2 matrices
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
c[i][j] = 0;
for(int k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
}
[Link](c[i][j] + " ");
}
[Link]();
}
}
7) Write a Java program to get the transpose of matrix?
public class TransposeMatrix{
public static void main(String args[]){
//creating a matrix
int original[][]={{1,3,4},{2,4,3},{3,4,5}};
//creating another matrix to store transpose of a matrix
int transpose[][]=new int[3][3]; //3 rows and 3 columns
//Code to transpose a matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
[Link]("Printing Matrix without transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](original[i][j]+" ");
}
[Link]();
}
[Link]("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](transpose[i][j]+" ");
}
[Link]();
}
}
}
8) Write a Java program to compare two strings?
public class CompareTwoStrings {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Enter first string");
String first = [Link]();
[Link]("Enter second string");
String second = [Link]();
compare(first,second);
}
public static void compare(String s1, String s2){
if([Link](s2)==0) {
[Link]("Strings are equal");
} else {
[Link]("Strings are not equal");
}
}
}
9) How to find whether a String ends with a specific character or text using Java program?
public class StringEndWith{
public static void main(String args[]) {
String s1 = "Java is a programming language";
//Check if string ends with particular character
boolean endsWithCharacter = [Link]("e");
[Link]("String ends with character 'e': " + endsWithCharacter);
//Check if string ends with particular text
boolean endsWithText = [Link]("java");
[Link]("String ends with String 'lang': " + endsWithText);
}
}
10) Write a Java program to demonstrate indexOf()?
public class IndexOfExample{
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the input string:");
String inputString = [Link]();
[Link]("Enter the sub string:");
String subString = [Link]();
int index = [Link](subString);
[Link]("Index of sub string is: " + index);
}
}
11) Write a Java program to demonstrate how to replace a string with another string?
public class ReplaceString{
public static void main(String args[]) {
String originalString = "Java for dummies";
String newString = [Link]("dummies","experts");
[Link]("Original string is: " + originalString);
[Link]("New String is: " + newString);
}
}
12) Write a Java program to split the given string?
class SplitString{
public static void main(String []args){
String strMain = "Java,C,Python,Perl";
String[] arrSplit = [Link](",");
for (int i=0; i < [Link]; i++)
{
[Link](arrSplit[i]);
}
}
}
13) Write a Java program to remove the spaces before and after the given string?
class RemoveSpacesInString{
public static void main(String []args){
String s1 = "Interview Questions for Java";
String newString = [Link]("\\s","");
[Link]("Old String: " + s1);
[Link]("New String: " + newString);
}
}
14) Write a Java program to convert all the characters in given string to lower case?
class ConvertToLowerCase{
public static void main(String []args){
String s1 = "Interview QUESTIONS";
String newString = [Link]();
[Link]("Old String: " + s1);
[Link]("New String: " + newString);
}
}
15) Write a Java program to demonstrate creating a method?
public class CreateMethodExample {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Enter the number");
int num = [Link]();
reverseNumber(num);
}
public static void reverseNumber(int number){
int reverse = 0;
while(number!=0){
int digit = number % 10;
reverse = reverse * 10 + digit;
number = number/10;
}
[Link]("Reversed number " + reverse);
}
}
16) Write a Java program to find the length of the given string?
class FindLength{
public static void main(String []args){
String s1 = "Interview Questions In Java";
int length = [Link]();
[Link]("Length of string is: " + length);
}
}
17) Write a Java program to concatenate the given strings?
class StringConcatenation{
public static void main(String []args){
String s1 = "Interview Questions In Java";
String s2 = " And Selenium";
String s3 = [Link](s2);
[Link]("After concatenation: "+ s3);
}
}
18) Write a Java program to replace a string?
class ReplaceString{
public static void main(String []args){
String s1 = "Interview Questions In Java";
String s2 = "Answers";
String s3 = [Link]("Questions","Answers");
[Link]("Original String: "+ s1);
[Link]("New String: "+ s3);
}
}
19) Write a Java program to demonstrate a Static block?
class StaticTest {
static int i;
int j;
// start of static block
static {
i = 10;
[Link]("static block called ");
}
// end of static block
}
class Main {
public static void main(String args[]) {
[Link](Test.i);
}
}
20) Explain the difference between static and instance methods in Java?
Instance method are methods which require an object of its class to be created before it can be called.
Static methods are the methods in Java that can be called without creating an object of class.

21) Write a Java program to demonstrate creating multiple classes?


public class A {
public static void print() {
[Link]("This is a method");
}
}
public class B {
public static void main(String args[]) {
print();
}
}
22) Write a Java program to demonstrate creating a constructor?
class ConstructorTest {
ConstructorTest(){
[Link]("Constructor called");
}
}
class Main
{
public static void main (String[] args)
{
ConstructorTest test = new ConstructorTest();
}
}
23) Write a Java program to demonstrate constructor overloading?
class Box
{
double width, height, depth;
int boxNo;
Box(double w, double h, double d, int num)
{
width = w;
height = h;
depth = d;
boxNo = num;
}
Box()
{
width = height = depth = 0;
}
Box(int num)
{
this();
boxNo = num;
}
public static void main(String[] args)
{
Box box1 = new Box(1);
[Link]([Link]);
}
}
24) Write a Java program to demonstrate Exception Handling?
public class ExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{[Link](e);}
}
}
25) Write a Java program to demonstrate throwing an exception?
class ThrowExceptionExample
{
public static void main(String[] args)throws InterruptedException
{
[Link](10000);
[Link]("Hello World");
}
}
 

FOLLOW US
 

Common questions

Powered by AI

Method overloading, demonstrated with constructors, allows a class to have more than one method (or constructor) with the same name but different parameters. This promotes flexibility and reusable code. In the example, one constructor initializes object dimensions while another initializes the object with default values or specifies unique identifiers. It enables objects of the same class to be instantiated in different ways, depending on the data available or the intended setup of the instance .

The 'reverseNumber' method provides a clear example of method utility and modularity in Java. It separates concerns by encapsulating the logic required to reverse digits of a number within a method, allowing for reusability and readability. By calling this method from the main function, it illustrates how complex operations can be simplified and abstracted, promoting clean code practices and facilitating easier debugging and testing .

Transposing a matrix involves swapping its rows with its columns, effectively flipping it over its diagonal. In Java, this can be achieved by iterating through the rows and columns of a matrix and assigning the value at position (i, j) in the original matrix to position (j, i) in the transposed matrix. This is useful in various mathematical computations and data structure transformations. The Java code for matrix transposition utilizes nested loops for swapping these values .

The 'String.split()' method in Java divides a string into an array of substrings based on a specified delimiter, simplifying text parsing and data manipulation. It is particularly useful in tokenizing input, processing CSV or tab-delimited files, and breaking down complex strings into manageable components for analysis. This function allows developers to transform strings into structured data formats efficiently, which is crucial in fields like data parsing, text processing, and developing APIs that interact with text data .

Matrix multiplication in Java involves taking two matrices and producing a third matrix by taking the dot product of rows and columns. This is implemented using three nested loops: the first for iterating through rows of the first matrix, the second for columns of the second matrix, and the third to sum the products of corresponding elements. The operation accumulates products in a new matrix which represents the multiplication result. This process is essential for simulations and graphical transformations .

A Java program determines if a number is a palindrome by reversing the digits of the number and checking if the reversed number is equal to the original number. The program uses a while loop to reverse the digits: it repeatedly extracts the last digit of the number by using modulo operation, constructs the reversed number by shifting its digits left and adding the extracted digit, and then removes the last digit from the original number by dividing it by 10. If the reversed number is equal to the original number, the number is a palindrome .

A static block, also known as a static initialization block, is used to initialize static variables in Java. It runs once when the class is loaded into memory before any instances of the class are created. This differs from instance initialization, where instance variables are initialized each time an instance of the class is created. Static blocks are often used to initialize static data or perform operations that are required only once. In contrast, instance initialization relates to preparing unique variable values for individual objects .

Matrix transposition is utilized in various fields, such as computer graphics, machine learning, and engineering. In these domains, transposition is often needed for aligning matrix data for matrix multiplication, simplifying matrix equations and transformations, and converting data formats. The Java implementation showcases this by clearly swapping matrix indices, allowing for easy manipulation of matrix forms, thus demonstrating the simplicity with which complex mathematical operations can be performed programmatically .

Floyd's Triangle is a right angled triangular array of natural numbers used in computer science for demonstration purposes. To print Floyd's Triangle in Java, you use nested loops: the outer loop runs through the number of rows, while the inner loop manages the numbers to be printed, which increment with each iteration. For instance, to print a Floyd's Triangle with a given number of rows, the Java code would utilize nested loops to fill each row, incrementing the number to be printed .

In Java, exception handling is performed using try-catch blocks, where risky code is placed within the try block and exceptions are caught in the catch block for handling-specific errors. For instance, the program encounters a division by zero error, which throws an ArithmeticException. The exception is caught in the catch block, allowing the program to print the exception message without crashing. This approach helps in managing runtime errors without abruptly terminating the program .

You might also like