Java Programming Interview Questions with Answers (Part 2)
Hello Friends, I hope you are safe and doing great work. Today, I will discuss part 2 of Java interview questions. In this section, I will explain the pattern of Java coding. It is a popular interview question, and I will try to explain it as easily as possible.
Question-1:- print * pattern.
I am going to discuss the following pattern.
1- First, we have to take two variables i and j. i is for rows and j is for columns. now, let us start printing this pattern step by step.
2- For loop ‘i’ we initialize with 0 till the num. num is here the number given as an input i.e. num=4.
3- One thing we have to notice is that in second row whose value is ‘i=1’ we have to print 2 ‘*’. One is for column =0 and the second is for column=1.
4- As usual we have to print 3 ‘*‘ in the next row.
5- When we check the value of num. it is the same as the total ‘*’ we have to print in each row.
package com.mycompany.java_practice_questions;
public class Prin_pattern {
public static void main(String[] args) {
//*
//**
//***
//****
for(int i=0; i<4; i++){ //for Rows
for(int j =0; j<i+1; j++){ //For Columns
System.out.print("*");
}
System.out.println();
}
}
}
Now I will explain the code I have written. First, we use 2 loops: one is "i" to print rows and the second is "j" to print columns. Additionally, we use a nested for loop.
Here I am writing ‘j<i+1' because if we check the very first image, the ‘i’ row is 1 more than the num value. It means that if we want to print the ‘j’ pattern we have to print it one more than the ‘i’ value.
one more thing we have to notice is that in our first System.out.print do not use ‘ln’ otherwise it prints each ‘*’ in a new line.