[{"data":1,"prerenderedAt":139},["ShallowReactive",2],{"qa-\u002Fjava\u002Ffundamentals\u002Fkeywords-modifiers":3},{"page":4,"siblings":123,"blog":136},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"questionsCount":113,"related":114,"seo":115,"seoDescription":116,"stem":117,"subtopic":118,"topic":119,"topicSlug":120,"updated":121,"__hash__":122},"qa\u002Fjava\u002Ffundamentals\u002Fkeywords-modifiers.md","Keywords Modifiers",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Java","java",{},true,4,"\u002Fjava\u002Ffundamentals\u002Fkeywords-modifiers",[23,28,32,36,40,44,48,52,57,61,65,69,73,77,81,85,89,93,97,101,105,109],{"id":24,"difficulty":25,"q":26,"a":27},"access-modifiers","easy","What are the four access modifiers in Java and what do they control?","Access modifiers control **visibility** — who can see a class, field, method,\nor constructor. There are four levels, from most to least restrictive:\n\n| Modifier | Same class | Same package | Subclass (other pkg) | Everywhere |\n| -------- | :--------: | :----------: | :------------------: | :--------: |\n| `private` | yes | no | no | no |\n| *(default)* | yes | yes | no | no |\n| `protected` | yes | yes | yes | no |\n| `public` | yes | yes | yes | yes |\n\n```java\npublic class Account {\n  private double balance;   \u002F\u002F only this class\n  String owner;             \u002F\u002F package-private (no keyword)\n  protected int id;         \u002F\u002F package + subclasses\n  public String getOwner() { return owner; } \u002F\u002F anyone\n}\n```\n\n\"Default\" (also called **package-private**) is what you get with **no keyword**\n— it is not a keyword itself. The guiding principle: declare everything as\n**private** as you can and widen only when there's a real need.\n",{"id":29,"difficulty":14,"q":30,"a":31},"private-vs-protected","What is the difference between private and protected?","**`private`** restricts a member to its **own class** — not even subclasses can\nsee it. **`protected`** widens that to the **same package plus any subclass**,\nincluding subclasses in a different package (the one case package-private\ndoesn't cover).\n\n```java\npackage base;\npublic class Animal {\n  private String dna;       \u002F\u002F hidden from everyone but Animal\n  protected String species; \u002F\u002F visible to subclasses & same package\n}\n\npackage zoo;\nclass Dog extends Animal {\n  void show() {\n    \u002F\u002F System.out.println(dna);     \u002F\u002F won't compile — private\n    System.out.println(species);     \u002F\u002F OK — protected, inherited\n  }\n}\n```\n\nUse `private` for true implementation detail and `protected` only when you\nintend a member to be part of the **inheritance contract**.\n",{"id":33,"difficulty":25,"q":34,"a":35},"static-meaning","What does the static keyword mean?","`static` binds a member to the **class itself** rather than to any instance.\nThere is exactly **one copy** shared by all objects, and you access it through\nthe class name — no `new` required. It applies to fields, methods, nested\nclasses, and initializer blocks.\n\n```java\nclass MathUtil {\n  static final double PI = 3.14159;   \u002F\u002F one shared constant\n  static int square(int n) {          \u002F\u002F call without an instance\n    return n * n;\n  }\n}\nMathUtil.square(5);   \u002F\u002F 25 — no object created\nMathUtil.PI;          \u002F\u002F shared field\n```\n\nA `static` method **can't use `this`** or access instance fields directly,\nbecause there's no particular object in play. Statics load with the class and\nlive for the program's lifetime.\n",{"id":37,"difficulty":14,"q":38,"a":39},"static-vs-instance","What is the difference between a static member and an instance member?","A **static** member belongs to the **class** — one shared copy for the whole\nprogram. An **instance** member belongs to each **object** — every `new` gets\nits own copy.\n\n```java\nclass Counter {\n  static int total;   \u002F\u002F one shared across all Counters\n  int id;             \u002F\u002F one per instance\n  Counter() { id = ++total; }\n}\nnew Counter(); \u002F\u002F id=1, total=1\nnew Counter(); \u002F\u002F id=2, total=2  (total is shared)\n```\n\nStatic methods can only touch static state; instance methods can touch both.\nYou can call a static member before any object exists, whereas instance members\nrequire an object. Mutable static state is shared globally, which makes it a\ncommon source of threading bugs and memory leaks.\n",{"id":41,"difficulty":14,"q":42,"a":43},"static-nested-class","What is the difference between a static nested class and an inner class?","A **`static` nested class** is a class declared `static` inside another; it does\n**not** hold a reference to an enclosing instance and can be created on its own.\nA non-static nested class (an **inner class**) is tied to an outer instance and\ncan access its members.\n\n```java\nclass Outer {\n  int x = 10;\n  static class Nested {        \u002F\u002F no link to an Outer instance\n    int sum(int a) { return a + 5; }\n  }\n  class Inner {                \u002F\u002F bound to an Outer instance\n    int read() { return x; }   \u002F\u002F can use outer's x\n  }\n}\nOuter.Nested n = new Outer.Nested();        \u002F\u002F no Outer needed\nOuter.Inner i = new Outer().new Inner();    \u002F\u002F needs an Outer\n```\n\nPrefer **`static` nested** unless the class genuinely needs the outer instance —\ninner classes silently retain the enclosing object, a frequent memory-leak\ncause.\n",{"id":45,"difficulty":14,"q":46,"a":47},"final-variable","What does final mean for a variable?","A `final` variable can be **assigned only once**. For a primitive that locks the\nvalue; for a reference it locks **which object** the variable points to — the\nobject itself can still be mutated.\n\n```java\nfinal int MAX = 10;     \u002F\u002F MAX = 11; would not compile\nfinal List\u003CString> xs = new ArrayList\u003C>();\nxs.add(\"ok\");           \u002F\u002F mutating the object is allowed\nxs = new ArrayList\u003C>(); \u002F\u002F reassigning the reference is not\n```\n\n`final` applies to local variables, fields, and method parameters, and it's\nrequired (or \"effectively final\" status is) for any local variable captured by\na lambda or anonymous class.\n",{"id":49,"difficulty":14,"q":50,"a":51},"final-method-class","What does final mean for a method or a class?","A **`final` method** can't be **overridden** by a subclass — it fixes the\nbehavior. A **`final` class** can't be **extended** at all (e.g. `String`,\n`Integer`). Both are tools for protecting invariants and enabling optimization.\n\n```java\nclass Base {\n  final void audit() { }    \u002F\u002F subclasses cannot override this\n}\nfinal class Money { }       \u002F\u002F cannot be subclassed\n\u002F\u002F class Cash extends Money {}  \u002F\u002F compile error\n```\n\nMaking a class `final` is a common way to guarantee **immutability** stays\nintact (no subclass can add mutable state or override behavior), and it lets the\ncompiler\u002FJIT inline `final` methods more aggressively.\n",{"id":53,"difficulty":54,"q":55,"a":56},"blank-final","hard","What is a blank final and a final parameter?","A **blank final** is a `final` field declared **without** an initializer; it\nmust then be assigned **exactly once** in every constructor (or an instance\ninitializer) before construction completes. A **final parameter** simply can't\nbe reassigned inside the method body.\n\n```java\nclass Point {\n  final int x;             \u002F\u002F blank final\n  Point(int x) { this.x = x; }   \u002F\u002F must be set here\n\n  int shift(final int by) {\n    \u002F\u002F by = by + 1;        \u002F\u002F illegal — final parameter\n    return x + by;\n  }\n}\n```\n\nBlank finals let you set an immutable field from constructor arguments rather\nthan a fixed literal — the backbone of immutable classes. Static blank finals\nmust be assigned in a `static` block.\n",{"id":58,"difficulty":54,"q":59,"a":60},"final-vs-immutable","Does final make an object immutable?","No. `final` only freezes the **reference**, not the **object's contents**. A\n`final` variable can't be reassigned, but if the object it points to is mutable,\nits state can still change.\n\n```java\nfinal StringBuilder sb = new StringBuilder(\"a\");\nsb.append(\"b\");        \u002F\u002F allowed — object is mutated\n\u002F\u002F sb = new StringBuilder(); \u002F\u002F not allowed — reference is final\n```\n\n**Immutability** is a stronger, design-level property: it requires all fields be\n`final` *and* private, no setters, defensive copies of mutable inputs\u002Foutputs,\nand usually a `final` class. `final` is one ingredient of immutability, not the\nwhole recipe.\n",{"id":62,"difficulty":25,"q":63,"a":64},"static-final-constants","How do you define a constant in Java?","The idiom is **`static final`** with an UPPER_SNAKE_CASE name. `static` gives\none shared copy; `final` makes it unassignable. The compiler can **inline**\n`static final` primitive and `String` constants for efficiency.\n\n```java\npublic class Config {\n  public static final int MAX_RETRIES = 3;\n  public static final String APP_NAME = \"Interviews\";\n}\n```\n\nRemember `final` on a reference only freezes the reference — a\n`static final List\u003CString> X = new ArrayList\u003C>()` can still be mutated. Use\n`List.of(...)` or `Collections.unmodifiableList` for a genuinely constant\ncollection.\n",{"id":66,"difficulty":14,"q":67,"a":68},"abstract-class-method","What does the abstract keyword mean for classes and methods?","An **`abstract` method** declares a signature with **no body** — subclasses must\nimplement it. An **`abstract` class** can't be **instantiated**; it exists to be\nextended and may mix abstract methods with concrete ones and state.\n\n```java\nabstract class Shape {\n  abstract double area();        \u002F\u002F no body — subclass must provide it\n  void describe() {              \u002F\u002F concrete method is allowed\n    System.out.println(\"area=\" + area());\n  }\n}\nclass Circle extends Shape {\n  double r;\n  double area() { return Math.PI * r * r; }  \u002F\u002F implementation\n}\n\u002F\u002F new Shape();  \u002F\u002F compile error — abstract class\n```\n\nAny class with even one abstract method **must** be declared `abstract`. Use it\nwhen you want shared code plus mandatory hooks for subclasses to fill in.\n",{"id":70,"difficulty":54,"q":71,"a":72},"abstract-final-conflict","Why can't a method be both abstract and final (or abstract and private\u002Fstatic)?","`abstract` means \"**must be overridden** by a subclass.\" The conflicting\nmodifiers all **prevent overriding**, so the combinations are contradictory and\nrejected at compile time:\n\n| Combination | Why it's illegal |\n| ----------- | ---------------- |\n| `abstract final` | `final` forbids overriding; `abstract` requires it |\n| `abstract static` | `static` methods aren't polymorphic \u002F can't be overridden |\n| `abstract private` | `private` isn't inherited, so it can't be overridden |\n| `abstract synchronized` | nothing to lock — there's no body |\n| `abstract native` | `native` *has* an (external) body; `abstract` has none |\n\n```java\nabstract class C {\n  \u002F\u002F abstract final void a();   \u002F\u002F error\n  \u002F\u002F abstract static void b();  \u002F\u002F error\n  \u002F\u002F abstract private void c(); \u002F\u002F error\n}\n```\n\nThe rule of thumb: `abstract` is only compatible with `public`\u002F`protected`\n(and package-private) — anything that keeps the method open to overriding.\n",{"id":74,"difficulty":14,"q":75,"a":76},"transient","What does the transient keyword do?","`transient` marks an instance field to be **skipped during serialization**. When\na `Serializable` object is written out, transient fields are ignored; on\ndeserialization they come back as their **default** (`0`, `false`, `null`).\n\n```java\nclass Session implements Serializable {\n  String user;                 \u002F\u002F serialized\n  transient String authToken;  \u002F\u002F NOT serialized — restored as null\n  transient int cacheSize;     \u002F\u002F restored as 0\n}\n```\n\nUse it for **sensitive data** (passwords, tokens), values you can **recompute**,\nor non-serializable fields you don't want to persist. `transient` has no effect\non `static` fields (statics aren't part of an instance's serialized state\nanyway).\n",{"id":78,"difficulty":54,"q":79,"a":80},"volatile","What does the volatile keyword guarantee?","`volatile` tells the JVM a field may be changed by **multiple threads**, so every\nread goes to **main memory** and every write is immediately **visible** to other\nthreads — no caching in a thread-local register. It also establishes a\n**happens-before** ordering, preventing certain instruction reorderings.\n\n```java\nclass Worker {\n  private volatile boolean running = true;  \u002F\u002F visibility guaranteed\n  void stop() { running = false; }          \u002F\u002F seen by the run() thread\n  void run() {\n    while (running) { \u002F* ... *\u002F }           \u002F\u002F won't loop forever\n  }\n}\n```\n\nWhat it does **not** give you is **atomicity** of compound actions:\n`volatile int x; x++;` is still a race (read-modify-write isn't atomic). For\nthat you need `synchronized` or the `Atomic*` classes. Use `volatile` for simple\nflags and the safe-publication of a single value.\n",{"id":82,"difficulty":14,"q":83,"a":84},"synchronized","What does the synchronized keyword do?","`synchronized` provides **mutual exclusion**: only one thread at a time can hold\na given object's **monitor lock**, so a synchronized block\u002Fmethod runs without\ninterference. It also gives visibility guarantees (a happens-before edge on lock\nrelease\u002Facquire).\n\n```java\nclass Counter {\n  private int count;\n  synchronized void inc() { count++; }   \u002F\u002F locks on 'this'\n\n  private final Object lock = new Object();\n  void update() {\n    synchronized (lock) {                \u002F\u002F locks on a private monitor\n      count += 2;\n    }\n  }\n}\n```\n\nA `synchronized` **method** locks `this` (or the `Class` object for a static\nmethod); a `synchronized` **block** locks the object you name. Prefer a private\nlock object over locking `this` to avoid outside code interfering with your lock.\n",{"id":86,"difficulty":25,"q":87,"a":88},"this-keyword","What is the this keyword used for?","`this` is a reference to the **current object**. Its three common uses:\ndisambiguating a field from a same-named parameter, passing the current object\nto another method, and calling another constructor of the same class\n(`this(...)`).\n\n```java\nclass Point {\n  int x, y;\n  Point(int x, int y) {\n    this.x = x;          \u002F\u002F field vs parameter\n    this.y = y;\n  }\n  Point() {\n    this(0, 0);          \u002F\u002F constructor chaining — must be first statement\n  }\n  Point self() { return this; } \u002F\u002F return the current object\n}\n```\n\n`this` is unavailable in a **`static`** context — there's no current instance.\nThe `this(...)` constructor call, if used, must be the **first** statement.\n",{"id":90,"difficulty":14,"q":91,"a":92},"super-keyword","What is the super keyword used for?","`super` refers to the **parent class**. It does two jobs: calling a superclass\n**constructor** (`super(...)`) and accessing an **overridden** method or hidden\nfield of the parent (`super.method()`).\n\n```java\nclass Animal {\n  String sound() { return \"...\"; }\n  Animal(String name) { \u002F* ... *\u002F }\n}\nclass Dog extends Animal {\n  Dog() {\n    super(\"Rex\");                 \u002F\u002F parent constructor — must be first\n  }\n  @Override String sound() {\n    return super.sound() + \"woof\"; \u002F\u002F call the parent's version\n  }\n}\n```\n\nIf you don't write `super(...)`, the compiler inserts an implicit no-arg\n`super()` — which is why a parent with **only** a parameterized constructor\nforces every subclass to call `super(...)` explicitly.\n",{"id":94,"difficulty":14,"q":95,"a":96},"instanceof","What does instanceof do, including pattern matching?","`instanceof` tests whether an object is an **instance** of a given type (or a\nsubtype), returning a `boolean`. Since Java 16, **pattern matching** lets you\nbind the result to a typed variable in one step, removing the manual cast.\n\n```java\nObject o = \"hello\";\n\nif (o instanceof String) {            \u002F\u002F classic form\n  String s = (String) o;              \u002F\u002F explicit cast needed\n  System.out.println(s.length());\n}\n\nif (o instanceof String s) {          \u002F\u002F pattern matching (Java 16+)\n  System.out.println(s.length());     \u002F\u002F 's' is already a String\n}\n```\n\nKey facts: `instanceof` on **`null`** is always `false` (so it's a built-in null\nguard), and it's the standard way to make a **downcast** safe before performing\nit.\n",{"id":98,"difficulty":54,"q":99,"a":100},"native-strictfp","What do the native and strictfp keywords do?","Both are rarely written but show up in interviews. **`native`** marks a method\nimplemented in **non-Java code** (typically C\u002FC++) via the JNI — it has no Java\nbody. **`strictfp`** forces floating-point math to follow strict **IEEE-754**\nrules for fully portable, reproducible results across platforms.\n\n```java\nclass Bridge {\n  native void readSensor();   \u002F\u002F body lives in a native library, no { }\n}\n\nstrictfp class Calc {         \u002F\u002F all FP ops here are platform-independent\n  double scale(double x) { return x * 1.1; }\n}\n```\n\n`native` is how the JDK itself reaches OS-level features. `strictfp` mattered\nbecause older JVMs could use wider intermediate precision; as of **Java 17** all\nfloating-point is strict by default, so the keyword is now effectively a no-op.\n",{"id":102,"difficulty":14,"q":103,"a":104},"reserved-unused","Which Java keywords are reserved but never used?","Two words are **reserved keywords** — so you can't use them as identifiers — yet\nthe language assigns them **no function**: **`goto`** and **`const`**.\n\n```java\n\u002F\u002F int goto = 5;   \u002F\u002F compile error — reserved word\n\u002F\u002F int const = 1;  \u002F\u002F compile error — reserved word\n```\n\nThey were reserved deliberately so that programmers coming from C\u002FC++ wouldn't\naccidentally use them and so the language could repurpose them later (it never\ndid). Java uses `final` instead of `const`, and structured control flow plus\n**labeled** `break`\u002F`continue` instead of `goto`.\n",{"id":106,"difficulty":14,"q":107,"a":108},"var-not-keyword","Is var a keyword in Java?","No — `var` (Java 10+) is a **reserved type name**, not a true keyword. That\ndistinction matters: because it isn't a keyword, you can still legally use `var`\nas a **variable, method, or package name** (just not as a class name). It\nprovides **local variable type inference**: the compiler infers the static type\nfrom the initializer.\n\n```java\nvar list = new ArrayList\u003CString>();  \u002F\u002F inferred ArrayList\u003CString>\nvar count = 10;                      \u002F\u002F int — still statically typed\n\nint var = 5;        \u002F\u002F legal! 'var' as an identifier\n\u002F\u002F var var = 5;     \u002F\u002F illegal — can't infer here\n```\n\nRestrictions: local variables **with an initializer** only — never fields, method\nparameters, return types, or `var x;` \u002F `var x = null;`. It's syntactic sugar,\nnot dynamic typing.\n",{"id":110,"difficulty":54,"q":111,"a":112},"combining-modifiers","Can you combine modifiers, and which combinations are illegal?","Many modifiers stack freely (`public static final`), but some combinations are\ncontradictory and rejected by the compiler. The conflicts cluster around\n`abstract` (which **requires** overriding) and the modifiers that **forbid** it.\n\n| Combination | Legal? | Reason |\n| ----------- | :----: | ------ |\n| `public static final` | yes | the classic constant |\n| `private static` | yes | class-scoped helper |\n| `abstract final` | no | one demands overriding, the other forbids it |\n| `abstract static` | no | static methods can't be overridden |\n| `abstract private` | no | private isn't inherited |\n| `final abstract` (class) | no | a final class can't be subclassed\u002Fextended |\n| two access modifiers | no | `public private int x;` is meaningless |\n\n```java\npublic static final int LIMIT = 5;   \u002F\u002F fine\n\u002F\u002F abstract final void f();          \u002F\u002F error — see above\n```\n\nRule of thumb: a member can have **at most one** access modifier, and `abstract`\nis incompatible with anything that closes the door to overriding.\n",22,null,{"description":11},"Java keywords and modifiers interview questions — access modifiers, static, final, abstract, the static vs instance distinction, transient and volatile, synchronized, and other reserved keywords.","java\u002Ffundamentals\u002Fkeywords-modifiers","Keywords & Modifiers","Fundamentals","fundamentals","2026-06-20","gFYBhAKx-MM5RxFGMrin7cBvG0hdlhczHc6Tp43_EFQ",[124,128,131,135],{"subtopic":125,"path":126,"order":127},"Data Types & Variables","\u002Fjava\u002Ffundamentals\u002Fdata-types-variables",1,{"subtopic":129,"path":130,"order":12},"Strings","\u002Fjava\u002Ffundamentals\u002Fstrings",{"subtopic":132,"path":133,"order":134},"Arrays","\u002Fjava\u002Ffundamentals\u002Farrays",3,{"subtopic":118,"path":21,"order":20},{"path":137,"title":138},"\u002Fblog\u002Fjava-keywords-modifiers-static-final","Java Keywords & Modifiers — Access, static, final & abstract Explained",1782244115280]