Java Basic Interview Questions And Answers

25 Java Basic Interview Questions And Answers – Core Java Interview Questions For Experienced from Codingcompiler. Test your Java knowledge by answering these tricky interview questions on Java. Let’s start learning core Java interview questions and prepare for Java interviews. All the best for your future and happy learning.

Table of Contents

Java Basic Interview Questions

    1. How many keywords are reserved by language, what are these words, which of them are not used?
    1. What characters can a variable name consist of (a valid identifier)?
    1. What does the word “initialization” mean?
    1. What are the main groups can be divided into data types?
    1. What primitive types do you know?
    1. What do you know about converting primitive data types, is there any data loss, can you convert a logical type?
    1. What values ​​are the variables initialized by default?
    1. How is the value of a variable passed (by reference / value)?
    1. What do you know about the main function, what are the necessary conditions for its definition?
    1. What logical operations and operators do you know?
    1. What is the difference between a brief and complete record of logical operators?
    1. What is a truth table?
    1. What is a ternary select statement?
    1. What unary and binary arithmetic operations do you know?
    1. What bitwise operations do you know?
    1. What is the role and rules for writing a select statement (switch)?
    1. What cycles do you know what are their differences?
    1. What is a “loop iteration”?
    1. What parameters does a for loop have? Can I omit them?
    1. What operator is used to stop the loop immediately?
    1. What operator is used to go to the next iteration of the loop?
    1. What is an array?
    1. What types of arrays do you know?
    1. What do you know about shells classes?
  1. What is boxing / unboxing?

Related Java Tutorials For Beginners

Introduction to Java Programming

Java Keywords Tutorial For Beginners

Java Data Types Tutorial For Beginners

Java Operators Tutorial For Beginners

Java Control Flow Statements Tutorial

Java Performance Tuning Tips

Java Class Tutorial For Beginners

Java Exceptions Tutorial For Beginners

Java Annotations Tutorial For Beginners

Java Generics Tutorial For Beginners

Java Enumeration Tutorial For Beginners

Java Class Instance Tutorial For Beginners

Java Basic Interview Questions And Answers

1. How many keywords are reserved in language, what are these words, which of them are not used?

50, two of them are not used: const, goto;

To memorize it:

    • Primitives (byte, short, int, long, char, float, double, boolean)
    • Loops and Branches (if, else, switch, case, default, while, do, break, continue, for)
    • Exceptions (try, catch, finally, throw, throws)
    • Scopes (private, protected, public)
    • Declaration \ Import (import, package, class, interface, extends, implements, static, final, void, abstract, native)
    • Create \ Return \ Call (new, return, this, super)
    • Multithreading (synchronized, volatile)
  • instanceof, enum, assert, transient, strictfp, const, goto
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

* not used; ** added in 1.2, *** added in 1.4, **** added in 5.0.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

2. What characters can a variable name consist of (a valid identifier)?

The name or identifier of a variable is a sequence of lowercase and uppercase Latin letters, numbers, and the symbols “$” and “_”. The variable name can begin with any of the listed characters, except for the digit .

It is technically possible to start a variable name also with “$” or “_”, however this is prohibited by the Java Code Conventions code convention. In addition, the dollar symbol “$”, by convention, is never used at all. By convention, the name of a variable must begin with a small letter (the names of classes begin with a capital letter). Spaces when naming variables are not allowed.

3. What does the word “initialization” mean?

Initialization  (from the English. Initialization , initiation) – creation, activation, provisioning, determination of the parameters. Bringing the program or device into a state of readiness for use.

From a Java perspective, allocating memory for an object, for example when creating MyClass myClass = new MyClass (). This will allocate memory for the myClass object (it will be initialized). Without initialization (new MyClass ()) write MyClass myClass; simply reserves the name (the myClass variable of type MyClass is declared).

4. What are the main groups can be divided data types?

5. What primitive types do you know?

Primitive

    • byte (integers, 1 byte, [-128, 127])
    • short (integers, 2 bytes, [-32768, 32767])
    • int (integers, 4 bytes, [-2147483648, 2147483647])
    • long (integers, 8 bytes, [-922372036854775808,922372036854775807])
    • float (real numbers, 4 bytes)
    • double (real numbers, 8 bytes)
    • char (Unicode character, 2 bytes, [0, 65536])
  • boolean (true / false value, using int, depends on JVM)

Reference . The reference types include all classes, interfaces, arrays.

https://stackoverflow.com/questions/383551/what-is-the-size-of-a-boolean-variable-in-java
boolean type: https://docs.oracle.com/javase/specs/jvms/ se8 / html / jvms-2.html # jvms-2.3.4

6. What do you know about the conversion of primitive data types, is there any data loss, is it possible to convert a logical type?

Conversion can be implicit and explicit (type casting). Implicit conversion can be performed if:

    1. types are compatible (for example, both are integers)
  1. the size of the “receiving” type is larger than that which is converted (the so-called “transformation with extension”)
1

2

int a = 123454;

double b =  a; //неявное преобразование – преобразование с расширением

Explicit conversion takes the form of a variable _ new _ type = ( new _ type ) variable name ;

1

2

int a;

byte b = (byte) a; //b будет остатком от деления a на диапазон byte, может быть потеря данных

Examples:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public static void typeConverterExample() {

       long a = 100L;

       double b = 300.0;

       Object ab = a + b;

       System.out.println(ab.getClass().getName() + ” value: ” + ab); //java.lang.Double value: 400.0

       double c = 1000.05;

       long d = 1000;

       Object cd = c+d;

       System.out.println(cd.getClass().getName() +” value: ” + cd);//java.lang.Double value: 2000.05

   }

   public static void typeNarrowing() {

       int a0 = 64;

       int a = 257;

       int a2 = 126;

       int a3 = 129;

       byte b0 = (byte) a0;

       byte b = (byte) a;

       byte b2 = (byte) a2;

       byte b3 = (byte) a3;

       System.out.println(b0+ ” ” + b + ” ” + b2 + ” ” + b3); //64 1 126 -127

       double c = 56.9876;

       int d = (int) c;

       System.out.println(d); //56

       long e = 1000L;

       float f = (float) e;

       System.out.println(f); //1000.0

   }

When raising the type byte> short; short> int; int> long; float> double; char> int information is not lost. In case of narrowing, loss of information is possible (see example above byte = (byte) int).

In various operations, types may be raised in order of “gain” to a more informative type. For example, adding int and double we get type double But there is a peculiarity, for example, by adding double (8 bytes) and long (8 bytes), Java will leave decimal places (double), and not a longer type. A similar example with the real part:

1

2

3

4

5

6

7

8

9

 long a = 100L;

       double b = a;

       Object ab = a + b;

       System.out.println(ab.getClass().getName() + ” value: ” + ab); //java.lang.Double value: 200.0

       float c = 100;

       long d = 1000;

       Object cd = c – d;

       System.out.println(cd.getClass().getName() +” value: ” + cd);//java.lang.Float value: -900.0

Briefly, you can write the following rules:

    1. byte, short, char in expressions always rise to int
    1. if the long type is involved in the expression, then the result will be given to this type
    1. if float is involved in the expression – the result is reduced to float
    1. if one of the operands is of type double, then the entire result will be cast to this type
  1. When choosing between the length and the ability to save the fractional part – the fractional part will be selected

7. What values ​​are the variables initialized by default?

Numbers are initialized to 0  or  0.0 . Objects (including String) – null , char – \ u0000 ; boolean – false ;

1

2

3

4

5

6

7

8

9

10

11

12

     class TestClass {

           int a; double b; float c; char d; String s; Object o; boolean e;

           @Override

           public String toString() {

               return “TestClass{” +

                       “a=” + a + “, b=” + b + “, c=” + c + “, d=” + d + “, s='” + s + ‘\” + “, o=” + o +”, e=” + e +’}’;

           }

       }

       TestClass testClass = new TestClass();

       System.out.println(testClass); //TestClass{a=0, b=0.0, c=0.0, d= , s=’null’, o=null, e=false}

   }

Core Java Interview Questions And Answers

8. How is the value of a variable transmitted (by reference / value)?

Constant holivar on this issue seems to be related to the translation into Russian of some terms, as well as the work of Java with primitives, strings and reference objects. In English, everything sounds strictly – Java is always pass-by-value . Usually, language features related to the understanding of primitives, references, and objects in Java (and the fact that some of them are immutable) cause a dispute. So:

    • Java conveys everything by value . Java never conveys anything by reference. Primitives, links, null – everything is passed by value, not by “link”.
    • Pass by value : When a parameter is passed to a method, the parameter is copied to another variable and it is passed to the method. Therefore, this is called “pass by value”.
  • Passing by reference : If we pass a reference type (object) to a method, then a copy of this object (reference) is also transmitted, which points to a certain area of ​​memory (the link can be called a “pointer”). Changing something in the memory area will change all objects that refer to this memory area. From here comes the name “pass by reference” , although the same value is transmitted, just the value is a pointer to the memory area.

Go through the example on stackoverflow (https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) and translate into Russian:

Suppose we have such a line that reserves the name myDog under the type Dog .

1 Dog myDog;

But this is not a physical object, but only a pointer to the type Dog. Now create (initialize) this object.

1

2

Dog myDog = new Dog(“Rover”);

foo(myDog);

Now myDog really occupies an area in memory (let there be a Dog @ 42 area ). By calling the foo (myDog) method, we pass a copy of  the pointer value to the memory area 42 .

1

2

3

4

5

public void foo(Dog someDog) {

   someDog.setName(“Max”); // AAA

   someDog = new Dog(“Fifi”);  // BBB

   someDog.setName(“Rowlf”);   // CCC

}

In the line // AAA we changed the value in memory 42 to “Max”.

In the line // BBB, we created a new object, which will now lie in another area of ​​memory (let it be Dog @ 74 ).

In the line // CCC, we changed the value in the memory area 74 . Obviously, the original myDog @ 42 object does not know anything about it, but it refers to the memory area already changed in the // AAA line and will now return the name “Max”.

Now another ambush – primitives and strings.

  • When a primitive is passed to a method, its copy is also transmitted (a copy of the value).
1

2

3

4

5

6

7

8

9

int x = 5;

int y = changeX(x)

//x=5;

//y=25;

private int changeX(int value) {

value = value * 5;

return value;

}

Created primitive x = 5 . Transferred to the method a copy of the value (i.e. 5 ). In the method multiplied by the number and returned it. The value of the primitive y will be equal to 25 , and the value of the primitive x = 5 (that is, it will not change).

The thing is, we passed the value (5), not the pointer to the memory area. Accordingly, the value of x should not have changed, since we did not change it (the method used a copy of the value).

  • The strings are immutable, i.e. unchangeable. When we assign a new value to a string, a new object will always be created in memory.

Another example of what happens when a parameter is passed to a method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

class TestClass {

           public ArrayList<Object> changeObjectValue(ArrayList<Object> objectValue) {

               objectValue.clear();

               objectValue.add(999);

               return objectValue;

           }

           public String changeStr(String str) {

               str = “NewString”;

               return str;

           }

           public int changeX(int x) {

               x = x*5;

               return x;

           }

       }

       TestClass testClass = new TestClass();

       ArrayList<Object> value = new ArrayList<Object>();

       value.add(23);

       String str = “FirstString”;

       int x = 2;

       System.out.println(value + ” ” + str + ” ” + x); //[23] FirstString 2

       ArrayList<Object> value2 = new ArrayList<Object>();

       value2 = value;

       value2 = testClass.changeObjectValue(value2);

       

       String str2 = str;

       str2 = testClass.changeStr(str2);

       

       int x2 = testClass.changeX(x);

       System.out.println(value + ” ” + str + ” ” + x); //[999] FirstString 2

       System.out.println(value2 + ” ” + str2 + ” ” + x2); //[999] NewString 10

       System.out.println(value.equals(value2) + ” ” + str.equals(str2) + ” ” + (x2 == x)); //true false false

    1. Create a reference value object and add an object to it (Integer = 23). We also create the string str = “FirstString”and the primitive number x = 2 .
    1. Separately, we create a value2 object and allocate memory for it; Now it looks like something like value = {ArrayList @ 450}, value2 = {ArrayList @ 453}, i.e. it is clear that these are different references to objects (different areas of memory).
  1. value2 = {ArrayList @ 450}, value = {ArrayList @ 450} after assignment, both objects refer to the same memory area. Now we will try to change them using methods in the test class.
    • Objects are transmitted by a copy of the pointer to the memory area. Since value and value2 point to one object in memory, then after a change in the changeObjectValue method of  one object, the second one will change.
    • The string (String) is always created new. Although str2 = str and pointed to one region at the beginning, but after changing str2 to a new value of NewString , the value of the first string remained the same.
  • Since primitive types are passed by copy of the value (in this case 2 ), then the change in the primitive type method did not affect the value of the initial variable x (the value in the memory area for x remained the same) .

If you still have questions, google on  pass-by-value.

9. What do you know about the main function, what are the necessary conditions for its definition?

Mandatory entry  public static void main ( String [ ] args ) { / * method body * / }

The main () method is the entry point to the program. There may be several main methods. Input parameters are just an array of strings. If this method is not present, then compilation is possible, but at startup it will be Error: Main method not found.

Related Java Interview Questions

  1. JSF Interview Questions
  2. JSP Interview Questions
  3. JPA Interview Questions
  4. Spring Framework Interview Questions
  5. Spring Boot Interview Questions
  6. Core Java Multiple Choice Questions
  7. 60 Java MCQ Questions And Answers
  8. Aricent Java Interview Questions
  9. Accenture Java Interview Questions
  10. Advanced Java Interview Questions For 5 8 10 Years Experienced
  11. Core Java Interview Questions For Experienced

Core Java Interview Questions And Answers For Freshers

10. What logical operations and operators do you know?

11. What is the difference between a brief and complete scheme for recording logical operators?

Logical operations:>, <, <=,> =, ==,! =;

Operator Description
& Boolean AND (AND)
&& Abbreviated AND
| Boolean OR (OR)
|| Short OR
^ Boolean XOR (Exclusive OR (OR))
! Logical unary NOT (NOT)
& = AND assignment
| = OR with assignment
^ = XOR with assignment
== Equally
! = Not equal
?: Ternary (ternary) conditional operator

If both operands are true, then the & and && operators return true.

If at least one operand is true, then the operators | and || return true.

Operators & and | always check the value of both operands. && and || are called short-circuit operators, since if the result of a boolean expression can be determined from the left operand, the right operand is not calculated.

Note: || and && can only be used in logical expressions.

12. What is a truth table?

A truth table is a table describing a logic function.

A B A | B A & B A ^ B ! A
false false false false false true
true false true false true false
false true true false true true
true true true true false false

13. What is the ternary selector operator?

In Java, there is also a special ternary conditional operator that can replace certain types of if-then-else operators — is it ?:

The ternary operator uses three operands. The expression is written in the following form:

logical condition ? expression1: expression2

If the logical condition is true , then expression1 is calculated and its result becomes the result of the execution of the entire operator. If the logical Condition is false , then expression2 is calculated , and its value becomes the result of the operator’s work. Both operands, expr1 and expr2, must return a value of the same (or compatible) type.

14. What unary and binary arithmetic operations do you know?

Unary operations are performed on one operand, binary operations on two operands, and ternary operations are performed on three operands. The operand is a variable or value (for example, a number) participating in an operation.

An example of unary arithmetic operations:

    • ++ – postfix / prefix increment, increases the value of an integer variable by 1;
    •  (double minus) – postfix / prefix decrement, reduces the value of an integer variable by 1;
    • + – leaves the sign of the number;
  • – changes the sign of a number.

The word postfix means that the operation will be applied to the operand after evaluating the entire expression in which the operand enters. Similarly, prefix means that the operation will be applied before evaluating the expression.

An example of binary arithmetic operations:

    • + – addition of numbers or strings;
    •   – subtraction of numbers;
    • * – multiplication of numbers;
    • / – division of numbers;
  • % – calculation of the remainder of the division of numbers.

The operation of calculating the remainder of the division is applicable to both integers and real.

15. What bitwise operations do you know?

~ Bitwise unary operator NOT
& Bitwise AND
& = Bitwise AND with assignment
| Bitwise OR
| = Bitwise OR with assignment
^ Bitwise XOR Exclusive
^ = Bitwise XOR with assignment
>> Shift to the right (division by 2 in the degree of shift)
>> = Shift right with assignment
>>> Shift right with padding with zeros
<< Shift left (multiply by 2 in the degree of shift)
<< = Shift left with assignment
>>> = Shift right with padding with zeros

Basic Java Interview Questions And Answers For Freshers

16. What is the role and rules for writing a select statement (switch)?

The switch statement compares the argument for equality with the proposed value.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

switch(expression) {

   case value1:

    Statements;

break;

case value2:

    Statements;

break;

case value3:

    Statements;

break;

default:

    Statement;

   break;

}

It is necessary to put a break; after the completion of the command body, otherwise the execution will be continued below in the lines.

17. What cycles do you know, what are their differences?

Java uses for, while, do-while loops.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

while(expression) {

   // statement(s)

}

do {

   // statement(s)

}

while(expression)

for(initialization; validation; increment) {

   // statements

}

for(Object object : objects) {

   // statements

}

do-while is always executed at least once, because check comes after the body of the loop.

18. What is “loop iteration”?

This is a one-time execution of the code located in the loop body.

19. What parameters does the for loop have? Can I omit them?

1

2

3

4

5

6

7

for(initialization; termination; increment) {

   //statement(s)

}

for(;;) {

}

Core Java Interview Questions And Answers For Experienced

20. What operator is used to immediately stop the cycle?

21. What operator is used to go to the next iteration of the loop?

break; – exit from the loop (does not affect the outer loop).

continue; – finishes code execution in this loop body. Go to the next iteration.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

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

               if (j == 2) {

                   System.out.println(“#A# i: ” + i + ” j: ” + j + ” break (end j loop). Will not see #C#”);

                   break;

               }

               if (j == 1) {

                   System.out.println(“#B# i: ” + i + ” j: ” + j + ” continue (j++).Will not see #C#”);

                   continue;

               }

               System.out.println(“#C# i: ” + i + ” j: ” + j);

           }

       }

#C# i: 0 j: 0

#B# i: 0 j: 1 continue (j++).Will not see #C#

#A# i: 0 j: 2 break (end j loop). Will not see #C#

#C# i: 1 j: 0

#B# i: 1 j: 1 continue (j++).Will not see #C#

#A# i: 1 j: 2 break (end j loop). Will not see #C#

#C# i: 2 j: 0

#B# i: 2 j: 1 continue (j++).Will not see #C#

#A# i: 2 j: 2 break (end j loop). Will not see #C#

22. What is an array?

An array (in some programming languages ​​also a table, row, matrix) is a type or data structure in the form of a set of components (array elements) located in memory directly behind each other. At the same time, access to individual elements of the array is carried out using indexing, that is, links to an array indicating the number (index) of the desired element. Due to this, unlike the list, an array is a structure with random access.

The dimension of the array is the number of indices required for unambiguous access to the element of the array. The shape or structure of the array is the number of dimensions plus the size (length) of the array for each dimension; can be represented by a one-dimensional array.

In Java, arrays are objects. This means that the name given to each array only indicates the address of some piece of data in memory. In addition to the address, nothing is stored in this variable. The array index, in fact, indicates how far it is necessary to retreat from the initial element of the array in memory in order to get to the desired element.

23. What types of arrays do you know?

In Java, one-dimensional and multi-dimensional arrays.

24. What do you know about shell classes?

For each primitive type there is a corresponding class ( Byte , Double , Float , Integer , Long , Short ). Numeric classes have a common ancestor – the abstract class Number, which describes six methods that return a numeric value contained in the class, reduced to the corresponding primitive type: byteValue () , doubleValue () , floatValue () , intValue () , longValue () , shortValue () . These methods are overridden in each of the six numeric wrapper classes.

25. What is boxing / unboxing?

This is an automatic conversion from primitive data types to reference and vice versa.

Must Read Java Interview Questions Books 2020

RELATED INTERVIEW QUESTIONS

  1. JSF Interview Questions
  2. JSP Interview Questions
  3. JPA Interview Questions
  4. Spring Framework Interview Questions
  5. Spring Boot Interview Questions
  6. Core Java Multiple Choice Questions
  7. 60 Java MCQ Questions And Answers
  8. Aricent Java Interview Questions
  9. Accenture Java Interview Questions
  10. Advanced Java Interview Questions For 5 8 10 Years Experienced
  11. Core Java Interview Questions For Experienced
  12. GIT Interview Questions And Answers
  13. Network Security Interview Questions
  14. CheckPoint Interview Questions
  15. Page Object Model Interview Questions
  16. Apache Pig Interview Questions
  17. Python Interview Questions And Answers
  18. Peoplesoft Integration Broker Interview Questions
  19. PeopleSoft Application Engine Interview Questions
  20. RSA enVision Interview Questions
  21. RSA SecurID Interview Questions
  22. Archer GRC Interview Questions
  23. RSA Archer Interview Questions
  24. Blockchain Interview Questions
  25. Commvault Interview Questions
  26. Peoplesoft Admin Interview Questions
  27. ZooKeeper Interview Questions
  28. Apache Kafka Interview Questions
  29. Couchbase Interview Questions
  30. IBM Bluemix Interview Questions
  31. Cloud Foundry Interview Questions
  32. Maven Interview Questions
  33. VirtualBox Interview Questions
  34. Laravel Interview Questions
  35. Logstash Interview Questions
  36. Elasticsearch Interview Questions
  37. Kibana Interview Questions

Leave a Comment