• Register
Welcome to Kodlogs Q&A, programming questions and answer website.

Most popular tags

java program python php javascript android c# r spring c mysql arrays python-3 tomcat ggplot2 numpy exception spring-boot jdbc eclipse ssl sockets string x html sql-server python-2 7 java-8 intellij-idea entity-framework macos pandas minecraft ios hibernate csv security json windows ssl-certificate heap-memory scikit-learn winforms illegalstateexception keytool matlab redirect code program junit pip maven ubuntu math facebook jquery cryptography sql asp list loop int net class https fatal-error struts java-applet runtime-error apache-spark pyspark garbage-collection sql-server-2005 for-loop quirks-mode internet-explorer-9 internet-explorer machine-learning keras indentation-error unit-testing android-studio jupyter-notebook virtualenv webclient visual-studio-2010 webpack compiler-errors numpy-ndarray curl vagrant aspnet dataframe nullpointerexception javafx jsp django jpa docker wordpress servlet indentation xcode typeerror scanner sum deployment socketexception git linux loops css util oracle cmd recursion search tcp syntax connection float datetime httpwebrequest main function number import file html5 elasticsearch-5 elasticsearch app-transport-security ios10 ios9 cdn cloudflare wampserver plpgsql salt-stack sysv parent-child android-edittext textview visual-studio-2012 android-workmanager unique-index tsql unity2d unity3d electron theano maven-compiler-plugin pickle assetbundle rstudio bar-chart python-tesseract tomcat6 primefaces solr easymock jvm-crash tomcat7 apache-httpclient-4 web-services woodstox discord jersey-2 prepared-statement resultset sencha-cmd sencha-touch-2 sencha-touch powermock fips apex x509certificate ibm-bpm websphere-7 file-permissions file-io accesscontrolexception grizzly atmosphere slick2d lwjgl informetica twitter-bootstrap-3 jax-rs resteasy spring-mvc spring-security-kerberos spring-security kerberos long-integer mapnik pytorch git-review vpython continuation homebrew xgboost conda visual-studio android-asynctask stack-trace user-interface jaxws-maven-plugin maven-3 maven-2 browser-notsupportedexception google-maps-api-3 google-maps visual-studio-code truststore firebase-authentication aws-organizations amazon-web-services php-7 string-formatting cplusplus visual-studio-2015 net-core net-mvc msbuild extension-methods foreign-keys windows-services react-redux reactjs inputstream facebook-graph-api entity-framework-4 reportingservices-2005 reporting-services mips linear-regression anova deep-learning block-device melt reshape2 floating-point webpack-dev-server javascrip 0-lollipop android-5 statsmodels avx eclipseide javafx-2 php-not-recognized laravel command-line tinyurl classnotfoundexception atom-editor android-emulator android-sdk-tools ionic2 cordova foobar2k tcplistener net-2 net-4 ole-db-provider export-to-excel openrowset windows-10 vagrantfile glmnet jvm-arguments global-variables orm classformatexception eof upstart qt ipv4 graphviz pydot atom curses unityeditor pandoc tesseract xls oledb redux spotify cxf wamp nio stacked prediction headless hyperlink outlook jackson keystore applicationcontext pipeline iis jstl encryption perfect-square objective-c carthage xcode8 indexing standard-deviation sudo xampp postgresql connector apple mdf kubernetes destructor gettime arithmeticexception gmail ioexception heuristics milliseconds reporting disk cpu npm modx-revolution goldsky modx prevnext javascript-dictionary stack-smashing device-monitor radio-button android-actionbaractivity android-activity android-fragments java-long unqualified-id ora-12154 javc c++ java nullpointerexception runtime-error drjava awt-eventqueue dsx math-pow ajquery nosuchelementexception appcompatactivity jsf jtextfield awt jpanel inputmismatchexception glassfish deque jupyter flask lvalue tensorflow gradle servlets netbeans simulation ibm factorial javax apache boot opengl virtualbox jvm margins 2147483647 mongodb cloud firebase plot plugins github processor automation crash card certificate pointers concatenation formatting debugging devices module testing color arraylist node sequence date caching expected build response ip directory algorithms release collections print figure casting url expression integer microsoft sorting sort read types replace js rest ajax exe excel dictionary message required database text variable time size dll system files table runtime static random code web map http error version 0 2
0 votes
13 views
java 8 interview questions
by (1.5k points)  
reshown by

5 Answers

0 votes
The first question is why is Java bytecode a bit slower than native code?

The Java bytecode is platform independent.

So, it can run unchanged on different platforms

It may not be optimized to run on a single platform like native code.

However, in future, advances in compiler and Java Virtual Machine

may bring the performance of Java bytecode closer to native code.

Question 2.

What are the three types of comments in Java language?

The first type is the multi-line comment. Any textsbetween /*

and */ is ignored by the compiler.

The second type is a single-line comment. Any

text following // to the end of the line is ignored by the compiler.

the third type is a documentation comment. Text between

/** and */ is ignored by the compiler,

but read by the javadoc tool to generate documentation.

Question 3.

Which statement could be used in place of multiple if statements in Java?

It is the switch statement.

This statement can have multiple expected values for an expression.

Each value can have its own set of statements to execute.

If the expression is not equal to any of the given values, the control goes through default and its statements are executed.

Question 4.

What is the difference between private and public access modifiers?

A method, a constructor or a variable may be declared as private or public.

Private means that the declared item is visible within the class only.

Public means that the declared item is visible to all Java classes.

Question 5.

What are the types of loops in Java?

One loop is the while loop.

At the beginning of the loop, it has a condition that is then followed by the body of the loop.

The while loop checks the condition and if the condition is true, the body of the loop is executed and it checks the condition again.

Once the condition becomes false, the loop execution is terminated.

The other type of loop in Java is a for loop. It has three parts.

Initialization, condition and increment followed by the body of the loop.

The for loop executes the body of the loop if the condition is true and stops executing if the condition becomes false.

The third type is a do-while loop.

It is similar to the while loop, but has a body of the loop followed by the condition.

Since it checks the condition after executing the body of the loop, it executes at least once.

Question 6. What is the enhanced for loop?

This is a simplified way of looping through the elements of an array.

It requires only two parts in the for statement.

The first part is a variable and the second part is the name of the array.

There is an example below.

Now, x is the variable

of the same data type as the array called myArray.

The enhanced for loop automatically loops through each element of the array.

So, we have String myArray and it has

five elements in it.

A, B, C, D and E..

The enhanced for loop says for String x in

myArray

System.out.println(x);

So, this is a simplified way of looping through the elements of an array.

Question 7.

What is a class constructor?

This is a method with the same name as a class. This method is called when a new object of the class is created.

The constructor contains initialization code to set private variables, to call private methods and so on.

There can be multiple constructors in a class and this is called overloading the constructors.

Each of these constructors has different parameters like different number of parameters or maybe parameters of different data types.

Question 8. What is the difference between final and static modifiers?

final requires that the class field or variable can be assigned a value only once and that is the final value.

Java throws a compile-time error if another statement to assign value to this variable is given in the program.

static shares a class field or variable across all instances of the class.

The static variable may be assigned a particular value in one object of the class and it retains the same

value in all other objects of that class.

A static variable can be used even if there is no existing object of the class.

Question 9. What is inheritance?

A class may inherit another class by using the extends keyword..

The former (that means the inheriting class) is called the subclass and

the inherited class is called the superclass.

All public members (that means fields and methods of the superclass) are available to the subclass without writing any code.

An

object variable of the superclass type may be assigned any object reference of the subclass type.

Question 10. What is an event handler?

The user can perform an action on a GUI element such as a button or a text box.

Such an action can be moving focus in or out of the element or pressing Enter.

The action is called an event.

An event handler is code associated with the GUI element and it executes when an event occurs.
by (8.9k points)  
0 votes
Let us get started. Question 11.

How can you add GUI elements to a Java application?

Java has an API called swing to provide GUI components such as text boxes,

check boxes, radio buttons, combo boxes and so on.

These components are available on importing javax.swing.*

The process to add a GUI element to a Java application is

1) Create a new object of the component class.

2) Add the object to the container and

3) Attach an event handler to the object.

Question 12. How can you accept user input to a Java application?

This can be done by importing the java.util.Scanner class.

The Scanner class has methods like nextInt, nextDouble, nextLine and so on

to accept inputs of different data types from the user into a variable.

Question 13. What methods are available to search within a string?

The string class in Java has a vast number of methods. There are many methods to search for characters within a string.

Examples of these methods include charAt,

contains, indexOf, lastIdexOf, startsWith and endsWith.

Question 14.

How do you draw graphics in a Java application?

Java has a built-in graphics object. This object has methods such as drawArc, drawImage,

drawLine, drawRect (for an empty rectangle), fillRect (for a solid rectangle),

drawPolygon, fillPolygon and so on.

These methods can be invoked to draw the respective lines and shapes in any desired color.

Question 15.

How can you work with files and folders in Java?

First, import the java.io.File library.

Then create an object of the File class.

We can point the File object to the required file or directory.

This object will have file's properties and methods.

A Scanner object can be created for the File object and used to fetch the contents in the file.

Question 16. In Java, how do you handle exceptions?

This is done with try and catch blocks. So there may be code, which if executed may throw an exception.

Such code is put inside a try block which is followed by a catch block containing the exception handler.

If the code throws an exception

when it is executed, the control flows to the catch block.

The try block may have one or more lines of code.

Each line of code

may have its own try block also.

There can be one or more catch blocks to handle different types of exceptions.

All such catch blocks immediately follow the try block.

Question 17. What is recursion?

A recursive method is one that calls itself.

Let us look at the example below.

Now here for a given integer input that is greater than 1,

this method sums all the integers from the input down to one.

Now,

let us say for this method, we give

the input argument as 2. So, it is going to add up all the numbers from 1 to 2. That is

1 + 2 is 3.

So, first if the input is 2, it checks if

2 is equal to 1? No. It goes to the else block. return 2 + sumAll (2-1),

which means the sumAll method calls itself. And this time it calls itself

with an input argument of 1.

Now, when the input argument is 1, it returns 1. So basically it returns 2 + 1. That is 3.

Now, there are a couple of items to note here. If n = 1, return 1.

This is the base case, which is where the recursion ends.

And here since we have the function calling itself, there is a recursion in this line of code.

Question 18.

What is the benefit of using a list instead of an array?

The Collections class has several useful methods that work on a list, but do not work on an array.

Some of these methods are

addAll, binarySearch, copy, fill, max, min, reverse, shuffle and sort.

Question 19.

How are Stack and PriorityQueue classes different?

First, the Stack.

A new Element can be added to the Stack by the push method.

The new element is always added at the top of the stack. In an existing stack, the top element can be removed by the pop

method.

The Stack has other methods to add and remove elements at specified positions within the Stack.

Now, the PriorityQueue class. In a PriorityQueue, a new element is added by the offer method.

This new element is always inserted at the bottom of the queue.

In an existing queue, the top element can be removed by using the poll method.

The queue does not have methods to add and remove elements at specified positions within the queue.

Question 20.

How can different code in a program be executed concurrently? That means at the same time.

This can be done using threads. A Java application can have multiple threads of execution

running at the same time.

A thread can be created by writing a class that implements Runnable

interface.

Which means we have to implement the run method of this interface.

Thereafter, a new thread can be created by instantiating a new Thread object.

A Thread object has a number of methods like setPriority and start.
by (8.9k points)  
0 votes
Java interview questions the question can be as basic as why there is why the

main method is always as public static void and what happens if we remove the

public or static from the main method and how basically it works you know

so in further sessions we will mostly cover the opes concept maybe the

Constructors etcetera the access modifiers so things like that in today's

session I'll cover these two things like why

main method is strictly this public static void and what is the static

keyword okay so quickly jump on to this so what i have done is i have created a

java project here there's a default package i am going to create a package

here let's say a package is interview questions

I'll create a class in class so so see that as soon as we created it

automatically I mean the Eclipse automatically create it as a public

static void why so as the theory says if we won't if we

won't declare it as a public it would not possible to you know to access it or

to call it who what calls it basically so as you can see this is Java Virtual

Machine ok whenever we exceeded the program so the JVM tries to check in the

class the first thing it checks is all the static variables or whatever is

there with the static so it will be loaded and basically if it is not public

then JVM would not able to access it so and and one more thing that it always

looked for the main method okay so whenever so whatever we have written

within the main it only gets executed if there is no main method it won't be

possible to execute a Java program so let's save it I'll show you like just a

minute okay now what happens if you try to run it as this see you won't get a

option even to run it as a Java program or java application okay as soon as we

put this it will tell you at least to run it as a java application now we will

play around this okay so let's say if we remove it if we remove the word if we

remove the access modifier public maybe next session I'll cover then access

modifiers but for now it is that's that consider that the public

says the the public is an access modifier and if we remove it what

happens okay because basically JVM has nothing to it it basically don't have

access because this method is not declared as public

okay let's put it back let's remove static from here

now if the static is not there there will be nothing to load okay

which means JVM will not have any method to access if it is not mentioned as a

static because basically what happens I'll cover the static part in this

question as well so let's just let's just check the behavior like what

happens okay if I don't if I remove the void see basically the error will be

thrown here because some return type is always it should be there okay and which

is void for the main class why void again the return type is void since it

does not make sense to have anything else when the Java program basically

when it when we terminate when the execution of this program get its

terminated then there is there's nothing else to call or to return okay so

basically there is no point in returning from main method to any other method of

class so that is why the return type is void

okay now main method so as I said the JVM will have always looked for the mean

keyword the method name is mean then it will pick it it's a static public static

and return type is no then we pick it now why we mentioned it as a string

argument here and that to array okay because the default pattern of you know

passing the argument is array type let's try to change

what happens if we change it to int type of array what happens see again JVM will

not understand it okay if we change it back to string or just try this as well

only string argument no only integer argument again no the only area type of

all argument if you pass as a string array then only it will understand now

check if it is there yes it is that the option to run it is a java application

so it only accepts the string array as an argument so sometimes people people

ask that why we have we are always writing as I string and array as a

argyus the argument you can protect anything
by (8.9k points)  
0 votes
this is just variable okay and there is one more way to do it is this way okay

so there is no hard and fast rule it's just the name that we always do so I

think as per the theory after Java 5 it it was made possible to declare it both

ways like we can do it like this and also we can do it like this okay now we

will play around this more let's say we are writing a program the first program

is always HelloWorld for the beginners

okay let's execute it fine now sometimes the question is asked that can we have

multiple main methods like can we create another main method here so let's try

this what I will do basically is create another main method what will happen it

will say rename method because you cannot have main method you can add like

two main methods in a java program it it does not it is not allowed in Java you

can probably overload the main method so overloading is another concept of like

another oops concept so that we may learn that we will probably learn later

that I will explain you later in later sessions for time being what we can do

is if you can see this is on the argument type is string array argument

if I simply remove the array it accepts why because here the argument was Eddie

as soon as I remove this it becomes only the string argument okay

so then it is allowed basically what is happening this main method is overloaded

here because it is only possible when the arguments are different now you can

have multiple main methods the only thing you need to make sure that the

argument type should be different here if I put it as an integer it won't

accept so let's say I am array just put it like that only

I am string I am integer now what should happen

is it gonna execute all of them what do you think because as I mentioned the JVM

will always pick the main method and it will only exit with whatever is there in

the main method but public static void main along with the argument is a string

of the area of string okay now if I executed it will only execute this part

it's not gonna it it is like you can see the syntax and syntactically it is

correct so it the compiler won't throw any error but Java will not pick this

and it will only execute this part over here let's try to execute this see only

this is getting executed we can probably call this here okay let's say main now

again another method main now there are two main type of there are two main

methods apart from just this one the error is because we have not passed the

argument so you have to match the argument as per whatever you have

mentioned here okay so it basically requires and what you're passing here is

a string okay sudhanshu I am let's say here I'll say I am what args okay so we

are passing the matching no matter you can man you can change the sequence

sequence doesn't matter the type of argument that you're passing is is what

is what matters okay

now there is again main method this one you can you you can use this again and

again a number of time you calls it it will it will be called and whatever the

implementation that you have done in this method we will be executed so here

let's say if I want to call this method okay the the argument is integer so

let's say 10 now there is no error if I put it as a string also it will work why

because in that case it this basically matches this particular method because

it has type of string so it will again reacts acute this one so we want to

execute both half-hour methods so let's pass one type as integer okay I am

so what will be the output now I am adding then this method will be called

this will say I am 20 and then this will this method will be called it will say I

I am Sudhanshu okay now let's execute this see hi I'm

Mary I am 20 I am so not you so what is happening is we have

basically overloaded this method by changing the arguments so what is

overloading I will quickly brief you here itself
by (8.9k points)  
0 votes
maybe we'll cover in later session in details method overloading is like a

method having same name with different arguments okay so which is called as

method overloading now you will play around the keyword

static it's a told you why can't I declare the static variables inside main

method in Java cannot declare the static variable within any method static

variable have to be declared as a at a class level okay so these are the thumb

rules that you cannot create you cannot declare any variable as a static with in

main method or any other method it should be declared on at a class level

you might have read that the static variables are shared by all objects of

that class same value is accessed by all objects change in value by one object is

also experienced by all objects okay so play around this as well now so

basically let's start with the negative scenario let's say what happens if I so

as the static word itself says I am static something is static right the

static main it's not dynamic it's not variable you cannot change it okay so in

Java also sorry my bad static static int I equals to 10

see there's error why it would say illegal modifier for parameter I only

final is permitted so that is something else like you know that is something

else to understand but basically it's not allowed here let's say so this is

not the main class we have just overloaded it so let's try to put it

here it will also not accept it because it is only so basically the question is

asked in interviews like can you mention a static variable inside the main method

or some of the methods so the answer is no it should be declared on a class

level so if I put it here see there is no error because I am putting it inside

the class not in the main method not in the other methods okay so it is

possibility now if we have declared the integer is10 let's let's just use it

okay for let's say if i'm calling i over here so basically what happens this i is

being passed over here okay and it will say i am I

I means 10 I am 10 right now see it won't be possible if if I create local

variable here and that's if I'm saying into J equals to 20 okay I can still

pass J from here but not from outside this method not even from here what it

will say cannot be resolved to a variable C because again now it's

possible because before we use it we have to Enosh

visualize it so here we are saying that J is equals to 20 this possible but even

outside this method we are accessing this that's if I say if I use J here

what will happen

let's see both both of the things actually inj what should be the behavior

if i use i it will simply take it as i basically because it is a static it is

at a class level if I put J over here this is this will not accept it it

because this method don't know what J is because J is mentioned is a local

variable in this class in this method sorry in the main method

if you mention it over here it will understand that what J is right here it

won't understand then because it is not if I simply put it as J is equals to 10

maybe 20 it is not fitted then it is not it is

nowhere because we have made it as a static if as soon as I remove the static

what will happen see you don't know what I earn what J is so that's why whatever

I have mentioned now again check ok let's execute and see what is the output

I am array the second thing main I means I is 10 so

I am 10 10 20 I am 20 I am Sancho Sancho then here it is

printed 10 and here 20 so basically everything is working okay

now what else okay let's say if I change the value of a static

variable can I change it let's try to change I is equal to 30 okay now what

will be the behavior here I have to see these are the what I would say like you

know whenever somebody ask you to Java questions they can they can ask all

these things these are very basics like you know when we have started learning

Java so they they they check your you know your logic and how how thoroughly

you have learned the basic things so they can you know they can ask a number

and number of things around this so you should at least have a good base that is

why I am you know manipulating and expanding things here so you know you

you should have a strong base of like what would be the behavior if I change

simply change if I simply manipulate things around my program because in the

written exam also we in the written exam for Java also we have seen that programs

like these are written and because basically here we can you know execute

in C the outputs but if we just go by the theory then it's very difficult to

understand so okay I'll show you what will happen now so let's understand

first that what will be the behavior if I do so so here I have initialize the

static is 10 but within this main method what I am doing is I'm changing the

value of I to 30 okay but here what because in main I

have change it to 30 does that mean this value of I will be changed for this

method as well for this map for the weather let's not discuss J and just

discussing I okay what will be let's comment out the J part altogether let's

see one not considered this bit here just play around this okay this one this

one also comment out now the only part is I equals to 10 here I have I have

overloaded the variable i equals to 30 I am passing I into the main this one

basically because it has the argument type as integer so this will get

executed this will anyways I don't know I know but what I meant to say is this

one will not get executed because we are not even calling this we have commented

out this one right the string type so what will happen now is only this method

will be executed and the main method also

so let's say in main what is the value of I I right that's executed see

because we're in the main method itself we are changing the value I equals to 30

and then we are calling the main right so within main also it is 30 and from

main method itself it is calling it is a 30 but if I simply the best method is

being called here right so this main method is called this value here is

passing this main okay let let us do one more thing I'll create one temporary

method just to explain it in a better way no argument I don't want any

argument here I don't want to pass any argument just a temp method okay now

what is the vet what will be the value of I in this method let's execute then

explain you oh we have not called this okay so since it is a static method we

can simply call this here so again we have declared this method as a static if

I as soon as I remove this static then again I will have to create the object

of a class and call this method but that is something we can learn later maybe

but for the time being just make it as a static and okay now what will happen

again 30 because we have basically overloaded it in the main method let's

remove it okay and put it over here and

I is equals to 10

that's execute and see everywhere it is 10 now sorry my back again 20 should be

here because 10 is already there

then why because we had we have I think yeah this is being called this argument

is being passed here I so let's remove this which means it's being called temp

so in temp also the value is getting changed if I would have called this

let's say if I would have called this before this method here I am changing

the value of I is equal to 20 right I am overloading it but this argument is

being passed here

10-10-10 right because at a class level this is being declared as ten right if I

overloaded it here okay this is being passed as missing so this one is getting

executed my that is why I was a bit confused if I must be doing something

wrong it should be here this method is actually it's not even called it's

remove it it's creating confusion now see what is happening okay

so I'll explain you now this main method is called it is a value of is10 so what

it does is basically it passes the value of is 10 over here but then we have

overloaded right this variable or you can say we have overwritten this

variable I equals to 20 right so this I is now 20 so at the first call itself

this is called first then this is printed right so here as soon as the

execution started started from this line here okay the first thing is called as

this one where in this particular bit is executed and it it has overwritten the

value of I to 20 so it has printed it as a 20 then we have printed the value of I

why it is 10 here because it has picked the value from this right which is

overwritten later which is overwritten within the scope of this method this

method here but as a static as per the static declaration of I the value is 10

so as soon as this as far as this bit is concerned the value of I is still 10 so

test printed 10 then it comes to the third method where it has again pick the

value as I from here as 10 so I hope you now understand like you know these are

the tricks and someone might ask you questions around this like you know they

can probably give you a program like this where and they have overwritten the

values and then they they will ask you what will be the output so you don't

have to get confused just put just try to you know understand the basics and

you will easily understand how how the program behaves and what will be the

exact output so yeah I think that's it for this session maybe in next session

we will cover the access modifiers further like what is public protected

and private so basically access modifiers in Java and further on we will
by (8.9k points)  
...