Try   HackMD

Java Basics: Primitives and Wrapper Classes

Java Basics

Primitives and Wrapper Classes

Primitive Types

byte

Wrapper Classes

short

int

long

float

double

char

boolean

Byte

Short

Integer

Long

Float

Double

Character

Boolean

Java Array:

Java Basics

Array Basics

Array Declaration

int[] arrayName;

int[] arrayName = new int[10];

int[] arrayName = {1, 2, 3, 4, 5};

Java Basics: Useful Classes and Class

Java Basics

Useful Classes

String

StringBuilder

BigDecimal

Class

Attributes

Getter and Setter

Constructor

Java Basics: OOP Concepts

Java Basics

OOP Concepts

Attributes

Getter and Setter

Constructor

Inheritance

extends

abstract class

super

Java Basics: Conditionals and Loops

Java Basics

Conditionals

if-else

switch

Loops

for-loop

initialization; condition; update

while-loop

condition

do-while loop

execute once then check condition

Java Basics: Methods and Keywords

Java Basics

Methods

Instance Method

Static Method

Static and Final Keywords

static final

final

Other Keyword Combinations

final method

final class

static class

static variable


1. What is the difference between static method and instance method?

Static Method

​•	Belongs to the class, not any particular instance.
​•	Can be called without creating an object of the class.
​•	Can access static data members and change their values.
class StaticExample { static int count = 0; static void showCount() { System.out.println("Count: " + count); } } public class Main { public static void main(String[] args) { StaticExample.showCount(); // Count: 0 StaticExample.count = 5; StaticExample.showCount(); // Count: 5 } }

Instance Method

​•	Belongs to an instance of the class.
​•	Requires an object of the class to be called.
​•	Can access instance variables and methods directly.
class InstanceExample { int count = 0; void showCount() { System.out.println("Count: " + count); } } public class Main { public static void main(String[] args) { InstanceExample obj = new InstanceExample(); obj.showCount(); // Count: 0 obj.count = 5; obj.showCount(); // Count: 5 } }

2. What is Abstraction?

Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object.

abstract class Vehicle { abstract void start(); } class Car extends Vehicle { void start() { System.out.println("Car started"); } } public class Main { public static void main(String[] args) { Vehicle myCar = new Car(); myCar.start(); // Car started } }

3. What is Polymorphism?

Polymorphism is the ability of an object to take on many forms. It allows methods to do different things based on the object it is acting upon.

abstract class Animal{ } interface Swimable { void swim() ; } interface Runnable { void run() ; } class Cat extends Animal implements Swimable,Runnable { @Override void swim() { System.out.println("Cat are swimming."); } @Override void run() { System.out.println("Cat are running."); } } class Dog extends Animal implements Swimable,Runnable { @Override void swim() { System.out.println("Dog are swimming."); } @Override void run() { System.out.println("Dog are running."); } } public class Main { public static void main(String[] args) { Animal myDog = new Dog(); myDog.swim(); // Dog are swimming. myDog.run(); // Dog are running. Animal myCat = new Cat(); myCat.swim(); // Cat are swimming. myCat.run(); // Cat are running. } }

4. What is the difference between abstract class and interface?

Abstract Class

​•	Can have both abstract and non-abstract methods.
​•	Can have instance variables.
​•	Can provide method implementations.
abstract class Animal { abstract void sound(); void eat() { System.out.println("Animal eats"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Dog barks dog.eat(); // Animal eats } }

Interface

​•	Can only have abstract methods (Java 8 onwards, can have default and static methods).
​•	Cannot have instance variables.
​•	Provides a way to achieve full abstraction.
interface Animal { void sound(); } class Dog implements Animal { public void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Dog barks } }

5. What is Inheritance?

Inheritance is a mechanism where one class acquires the properties and behaviors of a parent class.

class Animal { void eat() { System.out.println("Animal eats"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); // Animal eats dog.bark(); // Dog barks } }

6. What is the difference between class Object and class Objects?

Class Object

​•	The root class of the Java class hierarchy.
​•	Every class in Java is a subclass of Object.
​•	Provides basic methods like equals(), hashCode(), toString(), etc.
public class Main { public static void main(String[] args) { Object obj = new Object(); System.out.println(obj.toString()); // java.lang.Object@<hashcode> } }

Class Objects

​•	A utility class in java.util package.
​•	Provides static methods to operate on or return objects.
import java.util.Objects; public class Main { public static void main(String[] args) { String str = null; System.out.println(Objects.toString(str, "default")); // default } }

7. What is Encapsulation?

Encapsulation is the technique of wrapping the data (variables) and code acting on the data (methods) together as a single unit. It restricts direct access to some of an object’s components.

class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Main { public static void main(String[] args) { Person person = new Person(); person.setName("John"); System.out.println(person.getName()); // John } }

8. Based on APIE in Java, what is OOP?

OOP (Object-Oriented Programming)

Object-Oriented Programming is a paradigm centered around objects and classes. The four main principles of OOP are:

​•	Abstraction: Hiding the complex implementation details and showing only the essential features.
​•	Polymorphism: The ability of an object to take on many forms, allowing methods to do different things based on the object it is acting upon.
​•	Inheritance: A mechanism where one class acquires the properties and behaviors of a parent class.
​•	Encapsulation: Wrapping the data and code together as a single unit, restricting direct access to some of the object’s components.

9. What is the usage of @Override hashcode() and equals()?

hashCode()

The hashCode() method returns an integer hash code value for an object. It is used in hashing-based collections like HashMap, HashSet, and Hashtable to store and retrieve objects efficiently.

When you override the hashCode() method, you ensure that objects which are equal (according to the equals() method) produce the same hash code. This is crucial for maintaining the contract between hashCode() and equals().

equals()

The equals() method checks if two objects are equal. By default, the equals() method in the Object class checks for reference equality (i.e., whether the two references point to the same object).

When you override the equals() method, you can define what it means for two objects of your class to be considered equal. Typically, this involves comparing the values of relevant fields.

Example

Consider a class Person with fields name and age. To properly use objects of this class in a HashSet, you need to override both equals() and hashCode().

import java.util.Objects; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName(){ reutrn this.name; } public int getAge(){ return this.age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if(!(obj instanceOf Person)) return false; Person person = (Person)obj; return Objects.equals(obj.name,person.getName()) && Obejcts.equals(obj.age,person.getAge()); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{name='" + name + "', age=" + age + '}'; } } public class Main { public static void main(String[] args) { Person p1 = new Person("John", 25); Person p2 = new Person("John", 25); System.out.println(p1.equals(p2)); // true System.out.println(p1.hashCode() == p2.hashCode()); // true HashSet<Person> people = new HashSet<>(); people.add(p1); people.add(p2); System.out.println(people.size()); // 1 System.out.println(people); // [Person{name='John', age=25}] } }

Summary

​•	Override equals() to define when two objects should be considered equal based on their state.
​•	Override hashCode() to ensure objects that are equal according to equals() return the same hash code, facilitating correct behavior in hash-based collections.
​•	Proper implementation of both methods is crucial for objects used in collections like HashMap, HashSet, etc.