Java Essentials: A Beginner’s Guide to Key Concepts for Interview Success
- In this article, we’ll explore essential Java concepts that every beginner should know for their interviews. We’ll cover topics such as JDK, JRE, JVM, variables, this keyword, reading and displaying data, encapsulation, polymorphism (overloading/overriding), inheritance, super keyword, abstraction/interfaces, static and final keywords. Plus, stay tuned for upcoming articles where we’ll dive deeper into advanced topics like data structures and exception handling.
2. Java variables
- Java is case-sensitive which means that x and X are two different variables. In java, variable names can either start with: a letter, _, $ then a combination of letters, numbers, and the symbols _ and $. It should never start with a number.
- In Java, variables can be classified into two broad categories: primitive types and reference types.
Primitive types are the basic data types built into the Java language, such as int, double, boolean, char, etc. These types represent simple values like numbers, characters, and true/false values. They are called “primitive” because they are not objects and do not have methods.
Reference types, on the other hand, are objects that store references to memory locations where the objects are actually stored. These types include classes, arrays, strings, interfaces, and enums. Reference types are sometimes also referred to as objects because they are instances of a class.
3. This keyword
We use this keyword for two cases:
- If we want to differentiate between parameters to a method/constructor and instance variables that share the same name. In this case, this refers to the current object, the instance of that class. In this example, this.x refers to the x variable of the current object of MyProgram, and x refers to the constructor parameter.
public class MyProgram{
int x;
int y;
MyProgram(int x, int y){
this.x=x;
this.y=y;
}
}
- If we want to call one constructor in another constructor within the same class. Between parentheses, we specify the parameters of the constructor being called. In our case, we are calling the default constructor.
public class MyProgram{
MyProgram(){
x=0;
y=0;
}
MyProgram(int x, int y){
if(x<0 && y<0){
this(); // calling the constructor MyProgram()
}else{
this.x=x;
this.y=y;
}
}
4. Reading data / displaying data
4.1 Reading data :
- to read String we use next() / nextLine()
- to read int we use nextInt()
- to read double we use nextDouble()
- to read float we use nextFloat()
- to read char we use next().chartAt(0)
Difference between next() and nextLine()
In Java, next() and nextLine() are methods provided by the Scanner class to read input from the console or other input streams.
The main difference between both is that next() reads input up to the first whitespace character (space, tab, or newline), while nextLine() reads input up to the end of the line.
4.2 Displaying data
Printing each message on a new line:
System.out.println("Hello world 1");
System.out.println("Hello world 2");
Printing messages on the same line:
System.out.print("Hello world 1");
System.out.print("Hello world 2");
Printing formatted messages:
System.out.printf("The number is %d",3);
=> another way of doing it :
String message = String.format("The number is %d",3);
System.out.print(message);
5. Encapsulation
Encapsulation is a mechanism of object-oriented programming that allows us to give visibility levels to class members in order to determine the access privilege of these members outside of the class.
It is important to understand the access modifiers used for this matter:
- public: applicable to the class, attributes ( class variables), methods, and constructors. “public” means accessible anywhere outside the class.
- private: applicable to attributes and methods. “private” means accessible directly inside the class where it is declared only.
- protected: applicable to attributes and methods. “protected” means accessible directly inside the class where it is declared, its subclasses whether these subclasses are inside the same package or not, and within the classes of the same package.
- By default, if we don’t specify any access modifiers for a class, class variable, or method, its visibility is “package-private”. This means that the visibility is restricted to the classes in the same package.
- It is common to make constructors “public”, attributes “private”, and methods “public” to achieve encapsulation and control access to the class’s internals.
- We can define multiple classes in the same Java file, but only one of them can be declared as “public”, and its name must match the file name. The rest of the classes should have package-private access.
6. Polymorphism
Polymorphism is a mechanism of object-oriented programming that allows a method to have different behaviors based on where it is implemented. There are two levels to polymorphism:
- Compilation level polymorphism, is also known as overloading :
In Java, overloading refers to creating more than one method with the same name in the same class. Each method has different parameters, which can differ in type, number, or both. However, the return type of the method is not considered when overloading methods. If we attempt to create the same method twice with the same name and parameters but different return types, the compiler will raise an error, preventing us from compiling the code.
Here’s an example to illustrate it:
public class MyClass{
public int countNumbers(int x, int y){
// some code
}
public int countNumbers(int x, int y, int z){
// some code
}
public double countNumbers(double x, double y){
// some code
}
// not a polymorphism -- error
public void countNumbers(double x, double y){
// some code
}
}
2. Execution level polymorphism, is also known as overriding:
In Java, method overriding occurs when a subclass (child class) of a parent class inherits its methods and provides its own implementation. Method overriding retains the method signature (name, parameters, and return type) as defined in the parent class but changes its implementation or body to suit the subclass’s requirements.
7. Inheritance
In object-oriented programming, inheritance is a mechanism that allows a class to inherit the members (attributes and methods) of another class. We use the keyword extends to signify that a class is inheriting from a superclass.
public class ChildClass extends ParentClass{
}
- In Java, a subclass can inherit only the non-private members ( attributes and methods) of its parent class. However, It cannot inherit the constructor of the parent class.
- Method overriding in Java allows a subclass to provide its own implementation of a method inherited from its parent class. A subclass can also assign new values to inherited attributes, giving it flexibility in terms of implementation.
- In Java, when a method is declared abstract in a parent class, it must be overridden by the subclasses. This is because an abstract method has no implementation in the parent class, and the subclass must provide one.
- In Java, a subclass can inherit from only one parent class using the “extends” keyword. Multiple inheritance is not supported in Java, although a class can implement multiple interfaces.
// this is wrong
public class A extends B, C{
}
8. super keyword :
We use it in two cases.
- When a subclass overrides methods and redefines attributes of a parent class, but we want to call the original method or attribute of the parent class in its subclass, we can use the super keyword. For example, we can use “super.method()” or “super.attribute” to refer to the parent class’s method or attribute.
public class A{
int x=2;
public void display(){
System.out.println("Hello from parent class");
}
}
public class B extends A{
int x =3;
public void display(){
System.out.println("Hello from subclass");
}
public void myTest(){
System.out.println(x); // displays 3
System.out.println(super.x); // displays 2
display(); // displays : Hello from subclass
super.display; // displays : Hello from parent class
}
}
2. Although constructors cannot be inherited by subclasses, they can be called. We use “super()” to call the constructor of the parent class. It is important to note that Java automatically calls the default constructor (either the one that Java has by default for objects if no constructor has been created or the non-parameterized constructor we create in a parent class). However, if we create at least one parameterized constructor in the parent class, then we must explicitly call it inside the constructor of the child class using “super()”.
9. Abstraction/ interfaces
9.1 Abstraction
- abstract classes
An abstract class is a class that can’t be instantiated. Therefore we can’t use the keyword new with this type of class. We declare a class as abstract using the keyword abstract and we use this syntax:
abstract public class A{
}
=> An abstract class in Java can contain abstract and non-abstract methods and can only contain constant variables declared with the “final” and “static” keywords.
=> To create an object of an abstract class, we use its subclasses as follows:
let’s suppose we have an abstract class called A that has a subclass called C. Then we can do the following:
public void main(String[]args){
A a = new C();
/* We can always declare an object of type A but
we should assign it to an object of its subclass. */
}
- abstract methods
Abstract methods are declared without a body.
As an example:
abstract public class A{
abstract public void display(); // this is an abstract method
}
=> If a method is declared as abstract then it must exist within an abstract class.
=> If a method is abstract then it must be overridden in all the subclasses of its class.
9.2 Interfaces
We declare an interface with the keyword interface using the syntax:
public interface MyInterface{
}
=> we cannot create an instance of an interface in Java. Interfaces are abstract and don’t have any implementation, so there’s no object to instantiate.
public class A {
public void main(String[] args){
MyInterface i ; //right
new MyInterface(); //wrong
}
}
In Java, we can declare a variable of an interface type and assign it to an object of a class that implements that interface. For example:
interface MyInterface {
void myMethod();
}
class MyClass implements MyInterface {
public void myMethod() {
System.out.println("Hello world!");
}
}
public class Main {
public static void main(String[] args) {
MyInterface myObj = new MyClass();
myObj.myMethod(); // prints "Hello world!"
}
}
=> An interface can only contain abstract methods; by default, all its methods are public and abstract.
=> An interface can only contain constants attributes; by default, all its attributes are public static and final, they should always be assigned a value.
=> A class inherits properties of an interface using the keyword implements. A class implements one/many interfaces and must override all its methods.
=> An interface inherits properties of another interface using the keyword extends. An interface extends one/many interfaces.
10. Static/final
10.1 static Keyword
We use the keyword static with variables and methods:
- a static variable: is a class variable, one copy of this variable is created and shared among all the instances of the class. Its value is always the same for all its instances. Since it is a class variable, we can call it outside of its class using the class name: “className.variable”
- a static method is a method that is declared with the static keyword. It can only call static variables and static methods inside its body. We can call it outside of its class directly using the class name: “className.method”
10.2 final Keyword
We use the keyword final with classes, variables, and methods:
- a final class is a class that can’t have any subclasses that inherit its members.
- a final variable: is a variable whose value can’t be changed after its first assignment => a constant.
- a final method is a method that can’t be overridden.