Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

WikiQuora

WikiQuora Logo WikiQuora Logo

WikiQuora Navigation

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • Add group
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • Recent Questions
  • Most Answered
  • Bump Question
  • Answers
  • Most Visited
  • Most Voted
  • No Answers

WikiQuora Latest Questions

W3spoint99
  • 0
W3spoint99Begginer
Asked: January 17, 2025In: Angular

What is the difference between Promises and Observables?

  • 0

What is the difference between Promise and Observable in Angular? An example on each would be helpful in understanding both the cases. In what scenario can we use each case?

angularangular observableangular promisepromiserxjs
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 17, 2025 at 2:03 pm

    Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by Günter and @Relu. Since a code snippet is worth a thousand words, let’s go through the below example to understand theRead more

    Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by Günter and @Relu.

    Since a code snippet is worth a thousand words, let’s go through the below example to understand them easier.

    Thanks @Christoph Burgdorf for the awesome article


    Angular uses Rx.js Observables instead of promises for dealing with HTTP.

    Suppose that you are building a search function that should instantly show you results as you type. It sounds familiar, but there are a lot of challenges that come with that task.

    • We don’t want to hit the server endpoint every time user presses a key. It should flood them with a storm of HTTP requests. Basically, we only want to hit it once the user has stopped typing instead of with every keystroke.
    • Don’t hit the search endpoint with the same query parameters for subsequent requests.
    • Deal with out-of-order responses. When we have multiple requests in-flight at the same time we must account for cases where they come back in unexpected order. Imagine we first type computer, stop, a request goes out, we type car, stop, a request goes out. Now we have two requests in-flight. Unfortunately, the request that carries the results for computer comes back after the request that carries the results for car.

    The demo will simply consist of two files: app.ts and wikipedia-service.ts. In a real world scenario, we would most likely split things further up, though.


    Below is a Promise-based implementation that doesn’t handle any of the described edge cases.

    wikipedia-service.ts

    import { Injectable } from '@angular/core';
    import { URLSearchParams, Jsonp } from '@angular/http';
    
    @Injectable()
    export class WikipediaService {
      constructor(private jsonp: Jsonp) {}
    
      search (term: string) {
        var search = new URLSearchParams()
        search.set('action', 'opensearch');
        search.set('search', term);
        search.set('format', 'json');
        return this.jsonp
                    .get('http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK', { search })
                    .toPromise()
                    .then((response) => response.json()[1]);
      }
    }
    

    We are injecting the Jsonp service to make a GET request against the Wikipedia API with a given search term. Notice that we call toPromise in order to get from an Observable<Response> to a Promise<Response>. Eventually end up with a Promise<Array<string>> as the return type of our search method.

    app.ts

    // check the plnkr for the full list of imports
    import {...} from '...';
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Wikipedia Search</h2>
          <input #term type="text" (keyup)="search(term.value)">
          <ul>
            <li *ngFor="let item of items">{{item}}</li>
          </ul>
        </div>
      `
    })
    export class AppComponent {
      items: Array<string>;
    
      constructor(private wikipediaService: WikipediaService) {}
    
      search(term) {
        this.wikipediaService.search(term)
                             .then(items => this.items = items);
      }
    }
    

    There is not much of a surprise here either. We inject our WikipediaService and expose its functionality via a search method to the template. The template simply binds to keyup and calls search(term.value).

    We unwrap the result of the Promise that the search method of the WikipediaService returns and expose it as a simple array of strings to the template so that we can have *ngFor loop through it and build up a list for us.

    See the example of Promise-based implementation on Plunker


    Where Observables really shine

    Let’s change our code to not hammer the endpoint with every keystroke, but instead only send a request when the user stopped typing for 400 ms

    To unveil such super powers, we first need to get an Observable<string> that carries the search term that the user types in. Instead of manually binding to the keyup event, we can take advantage of Angular’s formControl directive. To use this directive, we first need to import the ReactiveFormsModule into our application module.

    app.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { JsonpModule } from '@angular/http';
    import { ReactiveFormsModule } from '@angular/forms';
    
    @NgModule({
      imports: [BrowserModule, JsonpModule, ReactiveFormsModule]
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Once imported, we can use formControl from within our template and set it to the name “term”.

    <input type="text" [formControl]="term"/>
    

    In our component, we create an instance of FormControl from @angular/form and expose it as a field under the name term on our component.

    Behind the scenes, term automatically exposes an Observable<string> as property valueChanges that we can subscribe to. Now that we have an Observable<string>, overcoming the user input is as easy as calling debounceTime(400) on our Observable. This will return a new Observable<string> that will only emit a new value when there haven’t been coming new values for 400 ms.

    export class App {
      items: Array<string>;
      term = new FormControl();
      constructor(private wikipediaService: WikipediaService) {
        this.term.valueChanges
                  .debounceTime(400)        // wait for 400 ms pause in events
                  .distinctUntilChanged()   // ignore if next search term is same as previous
                  .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
      }
    }
    

    It would be a waste of resources to send out another request for a search term that our application already shows the results for. All we have to do to achieve the desired behavior is to call the distinctUntilChanged operator right after we called debounceTime(400)

    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
2
  • 2 2 Answers
  • 522 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: January 17, 2025In: Angular

Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’?

  • 0

Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’? I have this simple input in my component which uses [(ngModel)] : <input type="text" [(ngModel)]="test" placeholder="foo" /> And I get the following error when I launch my app, even if the ...

angularangular formangular template form
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 17, 2025 at 2:02 pm

    For using [(ngModel)] in Angular 2, 4 & 5+, you need to import FormsModule from Angular form... Also, it is in this path under forms in the Angular repository on GitHub: angular / packages / forms / src / directives / ng_model.ts Probably this is not a very pleasurable for the AngularJS developeRead more

    For using [(ngModel)] in Angular 2, 4 & 5+, you need to import FormsModule from Angular form…

    Also, it is in this path under forms in the Angular repository on GitHub:

    angular / packages / forms / src / directives / ng_model.ts

    Probably this is not a very pleasurable for the AngularJS developers as you could use ng-model everywhere anytime before, but as Angular tries to separate modules to use whatever you’d like you to want to use at the time, ngModel is in FormsModule now.

    Also, if you are using ReactiveFormsModule it needs to import it too.

    So simply look for app.module.ts and make sure you have FormsModule imported in…

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';  // <<<< import it here
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule, FormsModule // <<<< And here
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    
    export class AppModule { }
    

    Also, these are the current starting comments for Angular4 ngModel in FormsModule:

    /**
     * `ngModel` forces an additional change detection run when its inputs change:
     * E.g.:
     * ```
     * <div>{{myModel.valid}}</div>
     * <input [(ngModel)]="myValue" #myModel="ngModel">
     * ```
     * I.e. `ngModel` can export itself on the element and then be used in the template.
     * Normally, this would result in expressions before the `input` that use the exported directive
     * to have and old value as they have been
     * dirty checked before. As this is a very common case for `ngModel`, we added this second change
     * detection run.
     *
     * Notes:
     * - this is just one extra run no matter how many `ngModel` have been changed.
     * - this is a general problem when using `exportAs` for directives!
     */
    

    If you’d like to use your input, not in a form, you can use it with ngModelOptions and make standalone true…

    [ngModelOptions]="{standalone: true}"
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
2
  • 2 2 Answers
  • 491 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: December 25, 2024In: Programmers

How to prevent SQL injection in PHP?

  • 0

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); That’s because the user can input something ...

mysqlphpsecuritysqlsql-injection
  1. Saralyn
    Saralyn Teacher
    Added an answer on December 25, 2024 at 10:08 am

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fulRead more

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

    You basically have two options to achieve this:

    1. Using PDO (for any supported database driver):
      $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
      $stmt->execute([ 'name' => $name ]);
      
      foreach ($stmt as $row) {
          // Do something with $row
      }
      
    2. Using MySQLi (for MySQL):
      Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:

      $result = $db->execute_query('SELECT * FROM users WHERE name = ?', [$name]);
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

      Up to PHP8.1:

      $stmt = $db->prepare('SELECT * FROM employees WHERE name = ?');
      $stmt->bind_param('s', $name); // 's' specifies variable type 'string'
      $stmt->execute();
      $result = $stmt->get_result();
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

    If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.


    Correctly setting up the connection

    PDO

    Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

    $dsn = 'mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4';
    $dbConnection = new PDO($dsn, 'user', 'password');
    
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    In the above example, the error mode isn’t strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.

    What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

    Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

    Mysqli

    For mysqli we have to follow the same routine:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
    $dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
    $dbConnection->set_charset('utf8mb4'); // charset
    

    Explanation

    The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

    The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

    Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

    Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

    Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

    $stmt = $db->prepare('INSERT INTO table (column) VALUES (:column)');
    $stmt->execute(['column' => $value]);
    

    Can prepared statements be used for dynamic queries?

    While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

    For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

    // Value whitelist
    // $dir can only be 'DESC', otherwise it will be 'ASC'
    if (empty($dir) || $dir !== 'DESC') {
       $dir = 'ASC';
    }
    
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 462 Views
Answer
Saralyn
  • 1
SaralynTeacher
Asked: April 27, 2025

Will AI replace programmers?

  • 1

As a coder, I have some nuanced opinions about AI. I’m an applications developer / designer, and I’ve been coding since I was a teenager. My first system was a Sinclair ZX80! My ...

AIartificial intelligencecodingJavajobprogrammer
  1. Saralyn
    Best Answer
    Saralyn Teacher
    Added an answer on April 27, 2025 at 1:58 pm

    AI is getting smarter, but replacing programmers entirely? That’s not happening anytime soon. What AI Can Do AI can already generate code, debug simple problems, and automate repetitive tasks. Tools like GitHub Copilot and ChatGPT can speed up development by suggesting solutions, writing boilerplateRead more

    AI is getting smarter, but replacing programmers entirely? That’s not happening anytime soon.

    What AI Can Do

    AI can already generate code, debug simple problems, and automate repetitive tasks. Tools like GitHub Copilot and ChatGPT can speed up development by suggesting solutions, writing boilerplate code, and even fixing errors. This means junior-level, repetitive coding tasks are becoming more automated.

    What AI Can’t Do

    Programming isn’t just about writing code—it’s about solving complex problems, understanding user needs, designing scalable systems, and making strategic decisions. AI lacks:

    • Creativity & Critical Thinking – AI can write code, but it doesn’t understand why one approach is better than another.
    • Problem-Solving Skills – Real-world software development isn’t just about syntax; it’s about architecture, security, and optimization.
    • Collaboration & Communication – AI can’t talk to stakeholders, understand business goals, or lead a team.

    The Future of Programming

    Instead of replacing programmers, AI will enhance them. Future programmers will spend less time on repetitive coding and more time on high-level design, debugging, and decision-making. AI will become a powerful assistant, not a replacement.

    Who Should Be Worried?

    • Low-skill, copy-paste coders – If your job is just Googling and pasting Stack Overflow answers, AI might replace you.
    • Routine, repetitive coding jobs – Simple automation tasks are already being taken over by AI.

    Who Will Thrive?

    • Problem-solvers and architects – Those who design, analyze, and optimize systems.
    • Developers who adapt to AI tools – The best programmers will use AI to be 10x more productive.

    Bottom Line

    AI won’t replace programmers—it will replace bad programmers. The best developers will learn to work alongside AI, using it as a tool to build even better software.

    See less
      • 1
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 425 Views
Answer
Saralyn
  • 1
SaralynTeacher
Asked: April 27, 2025

Should I learn Java or Kotlin in order to develop Android apps?

  • 1

Go Easy with Kotlin, create as many as Class in .kt but if you are having problem with, then also create some class in .java There is no issue if your app has both the classes, ...

AndroidDevelopmentJavaKotlin
  1. Saralyn
    Saralyn Teacher
    Added an answer on April 27, 2025 at 2:01 pm

    Learn Java if: ✅ You want to work on enterprise applications. ✅ You are interested in cloud computing, web services, and microservices. ✅ You prefer a well-established language with strong community support. Learn Kotlin if: ✅ You want to specialize in Android development. ✅ You prefer a modern, conRead more

    Learn Java if:

    ✅ You want to work on enterprise applications.

    ✅ You are interested in cloud computing, web services, and microservices.

    ✅ You prefer a well-established language with strong community support.

    Learn Kotlin if:

    ✅ You want to specialize in Android development.

    ✅ You prefer a modern, concise syntax.

    ✅ You want to explore functional programming & modern backend frameworks.

    Can You Learn Both?

    Yes! Java and Kotlin are interoperable, meaning you can use them together in the same project. Many companies use Java for backend and Kotlin for Android development.

    If you have time, learning both will make you a more versatile developer.

    Final Thoughts

    Both Java and Kotlin have their strengths. In 2025:

    • Java remains strong in enterprise, backend, and cloud applications.
    • Kotlin dominates Android development and is growing in backend applications.

    🚀 Best approach? Start with Java if you’re new, then explore Kotlin to expand your skill set. 🚀

    See less
      • 1
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 420 Views
Answer
Saralyn
  • 0
SaralynTeacher
Asked: December 24, 2024In: Programmers

What is a NullPointerException?

  • 0

Javanullpointerexception
  1. W3spoint99
    W3spoint99 Begginer
    Added an answer on December 24, 2024 at 8:11 am

    According To Java Docs: Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying theRead more

    According To Java Docs:

    Thrown when an application attempts to use null in a case where an object is required. These include:

    • Calling the instance method of a null object.
    • Accessing or modifying the field of a null object.
    • Taking the length of null as if it were an array.
    • Accessing or modifying the slots of null as if it were an array.
    • Throwing null as if it were a Throwable value.

    Applications should throw instances of this class to indicate other illegal uses of the null object.

    It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception.

    SynchronizedStatement:
        synchronized ( Expression ) Block

    Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

    There are two overarching types of variables in Java:

    1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.
    2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

    Consider the following code where you declare a variable of primitive type int and don’t initialize it:

    int x;
    int y = x + x;

    These two lines will crash the program because no value is specified for x and we are trying to use x‘s value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

    Now here is where things get interesting. Reference variables can be set to null which means “I am referencing nothing“. You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

    If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

    The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

    Take the following code:

    Integer num;
    num = new Integer(10);

    The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

    In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.

    If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that “num may not have been initialized,” but sometimes you may write code that does not directly create the object.

    For instance, you may have a method as follows:

    public void doSomething(SomeObject obj) {
       // Do something to obj, assumes obj is not null
       obj.myMethod();
    }

    In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

    doSomething(null);

    In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

    If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it’s a programmer error and the programmer will need that information for debugging purposes.

    In addition to NullPointerExceptions thrown as a result of the method’s logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

    // Throws an NPE with a custom error message if obj is null
    Objects.requireNonNull(obj, "obj must not be null");

    Note that it’s helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

    Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

    public void doSomething(SomeObject obj) {
        if(obj == null) {
           // Do something
        } else {
           // Do something else
        }
    }

    Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

    In Java 14, the following is a sample NullPointerException Exception message:

    in thread “main” java.lang.NullPointerException: Cannot invoke “java.util.List.size()” because “list” is null

    List of situations that cause a NullPointerException to occur

    Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:

    • Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don’t count!)
    • Calling an instance method of a null reference. (static methods don’t count!)
    • throw null;
    • Accessing elements of a null array.
    • Synchronising on null – synchronized (someNullReference) { ... }
    • Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
    • An unboxing conversion throws a NullPointerException if the boxed value is null.
    • Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
      class Outer {
          class Inner {}
      }
      class ChildOfInner extends Outer.Inner {
          ChildOfInner(Outer o) { 
              o.super(); // if o is null, NPE gets thrown
          }
      }
    • Using a for (element : iterable) loop to loop through a null collection/array.
    • switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.
    • foo.new SomeInnerClass() throws a NullPointerException when foo is null.
    • Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.

    A note from the JLS here says that, someInstance.someStaticMethod() doesn’t throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!

    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 389 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: January 8, 2025In: SpringBoot

How to access a value defined in the application.properties file in Spring Boot

  • 0

How can I access values provided in application.properties, like logging.level.org.springframework.web: DEBUG logging.level.org.hibernate: ERROR logging.file=${HOME}/application.log userBucket.path=${HOME}/bucket For instance, I want to access userBucket.path in my main program in a Spring Boot application.

application.propertiesJavaproperties filespringspringboot
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 8, 2025 at 4:20 pm

    Option 1: You can use the @Value annotation and access the property in whichever Spring bean you're using @Value("${userBucket.path}") private String userBucketPath; The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.   Option 2: AnotherRead more

    Option 1:

    You can use the @Value annotation and access the property in whichever Spring bean you’re using

    @Value("${userBucket.path}")
    private String userBucketPath;
    

    The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.

     

    Option 2:

    Another way is injecting org.springframework.core.env.Environment to your bean.

    @Autowired
    private Environment env;
    ....
    
    public void method() {
        .....  
        String path = env.getProperty("userBucket.path");
        .....
    }
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 305 Views
Answer
Load More Questions

Sidebar

Ask A Question
  • Popular
  • Answers
  • W3spoint99

    What is the difference between Promises and Observables?

    • 2 Answers
  • W3spoint99

    Can't bind to 'ngModel' since it isn't a known property ...

    • 2 Answers
  • W3spoint99

    How to prevent SQL injection in PHP?

    • 1 Answer
  • Saralyn
    Saralyn added an answer Learn Java if: ✅ You want to work on enterprise applications.… April 27, 2025 at 2:01 pm
  • Saralyn
    Saralyn added an answer AI is getting smarter, but replacing programmers entirely? That’s not… April 27, 2025 at 1:58 pm
  • Saralyn
    Saralyn added an answer Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature… January 17, 2025 at 2:03 pm

Trending Tags

AI angular application.properties arrays artificial intelligence coding how Java javascript machine learning mysql nullpointerexception php programmer python reactjs spring springboot sql string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

  • About US
  • Privacy Policy
  • Questions
  • Recent Questions
  • Web Stories

© 2025 WikiQuora.Com. All Rights Reserved