Until now, our Java programs knew all the values in advance. But real programs become useful only when they can listen to the user. Think about real life: 📝 A form is meaningful only when someone fills it. 🏧 An ATM works only after you enter details. A Java program also needs a way to listen 👂. That’s where user input comes in. 🛠️ 𝐔𝐬𝐞𝐫 𝐈𝐧𝐩𝐮𝐭 𝐢𝐧 𝐉𝐚𝐯𝐚 (𝐔𝐬𝐢𝐧𝐠 𝐒𝐜𝐚𝐧𝐧𝐞𝐫) Java provides a built-in class called Scanner to read input from the user while the program is running. There’s a simple flow involved: -->𝘐𝘮𝘱𝘰𝘳𝘵 𝘵𝘩𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘤𝘭𝘢𝘴𝘴 Before using Scanner, Java must be told where it comes from.This is done using import java.util.Scanner; -->𝘊𝘳𝘦𝘢𝘵𝘦 𝘢 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘰𝘣𝘫𝘦𝘤𝘵 The Scanner object is created using System.in , which means input will be read from the keyboard ⌨️. -->𝘙𝘦𝘢𝘥 𝘶𝘴𝘦𝘳 𝘪𝘯𝘱𝘶𝘵 Different methods are used based on the data type: • nextLine() → text • nextInt() → whole numbers • nextDouble() → decimal values -->𝘜𝘴𝘦 𝘵𝘩𝘦 𝘪𝘯𝘱𝘶𝘵 Once the input is stored in variables, the program can display it, compare it, or apply logic ⚙️. -->𝘊𝘭𝘰𝘴𝘦 𝘵𝘩𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 Closing the Scanner releases the input resource after the program finishes ✅. This small setup is what transforms a static program into an interactive one ✨. I’ve also attached a simple Java program that takes input from the user and uses it - feel free to go through it for better understanding. #Java #CoreJava #JavaBasics #LearningJourney #Programming #BuildInPublic
Java User Input Basics: Scanner Class and Methods
More Relevant Posts
-
Simple code. Subtle behavior. Easy to misjudge. Two similar Java methods. Two completely different outputs. Case 1-> public static int tricky1() { int x = 10; try { return x; } finally { x = 50; } } Output: 10 Explanation: When return x executes, Java evaluates and stores the value (10) first. After that, the finally block runs. Even though x becomes 50 inside finally, it does not change the already prepared return value. Case 2-> public static int tricky2() { try { return 10; } finally { return 30; } } Output: 30 Explanation: If finally contains a return statement, it overrides any previous return from try or catch. This is why returning from finally is considered bad practice — it can override results and even hide exceptions. #Java #CoreJava
To view or add a comment, sign in
-
🔹 Pass by Value vs Pass by Reference in Java • In Java, everything is Pass by Value. • For primitive types (int, double, char, etc.), Java sends a copy of the actual value. • Any changes inside the method will NOT affect the original variable. • For objects, Java sends a copy of the reference (memory address). • Both original reference and method reference point to the same object in heap memory. • If you modify the object’s data inside the method, the change is reflected outside the method. • If you assign a new object inside the method, the original reference will NOT change. 🧠 Easy Recall Trick Primitive → Copy of Value → No Change Object → Copy of Address → Object Data Can Change #TapAcademy Java #CoreJava #ProgrammingConcepts #PassByValue #InterviewPreparation #JavaDeveloper #WomenInTech #LearningJourney
To view or add a comment, sign in
-
-
🚀 Java 8 Streams – Word Frequency in a Sentence Here’s a classic interview-style problem 👇 🧩 Input: String str = "I am learning Streams API in JAVA JAVA"; 🎯 Goal: Count the frequency of each word using the power of Java Streams API. At first, we might think of using a Map and a loop. But with Java 8 Streams, we can make it expressive and concise. 💡 Solution: String str = "I am learning Streams API in JAVA JAVA"; Map<String, Long> wordCount = Arrays.stream(str.split(" ")) .collect(Collectors.groupingBy( word -> word, Collectors.counting())); wordCount.forEach((key, value) -> System.out.println(key + " : " + value)); 🔎 What’s happening here? • split(" ") → Breaks sentence into words • stream() → Creates a stream • groupingBy() → Groups identical words • counting() → Counts occurrences Simple. Clean. Powerful ✨ Want to make it better? You could: 1️⃣ Convert everything to lowercase to make it case-insensitive Problems like this show how beautifully Streams handle data transformation with minimal code. #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #LearningJourney #LearnWithMe
To view or add a comment, sign in
-
-
Is Java a compiled language or an interpreted one? Both. Confused? Yes, Java is both compiled as well as interpreted language. This is what makes it platform-independent. Java Code >> Compile (javac) >> Bytecode (portable code) >> Interpret (platform specific) >> Machine Code >> Execute. Normal: 1. Java Compiler (javac) compiles Java code to Bytecode (which is platform-independent). 2. Java Interpreter (java) interprets this bytecode (line-by-line) & convert it to Machine language. 3. Execute. Exception: JIT (Just In Time) Compiler 1. JVM maintains the count for no of times a function is executed. 2. If it exceeds the limit then JIT directly compiles the Java code into Machine language. No Interpretation. In General, • Compile: Source code >> Optimized Object Code (can be machine code or other optimized code) • Interpret: Source Code >> Machine Code (to be executed)
To view or add a comment, sign in
-
Day 11 - What I Learned In a Day(JAVA) Today I learned that Java variables are classified into two areas and understood their scope. 1️⃣ Global Area (Instance Variable) Declared inside the class but outside methods. Accessible by all methods inside the class. Scope: Entire class. Memory is created when the object is created. 2️⃣ Local Area (Local Variable) Declared inside a method, constructor, or block. Accessible only inside that method or block. Scope: Limited to that block only. Memory is created when the method runs. Types of Variables in Java (Based on Scope): 1️⃣ Local Variable Declared inside a method. Used only inside that method. Cannot be used outside the method. 2️⃣ Non-Static Variable (Instance Variable) Declared inside the class but outside methods. Belongs to the object. Each object has its own copy. 3️⃣Static Variable Declared using static keyword. Belongs to the class. One copy is shared by all objects. Three Important Statements in Java (Variables): 1️⃣ Declaration Creating a variable. You are telling Java the type and name of the variable. No value is given. Example: int a; 2️⃣ Initialization Giving a value to a variable. The variable must already be declared. Example: a = 10; 3️⃣ Declaration + Initialization Creating the variable and giving value at the same time. Example: int a = 10; Practiced 👇 #Java #Variables #Programming #CodingJourney
To view or add a comment, sign in
-
Mutable vs Immutable Strings in Java Strings are widely used in Java. Based on modification ability, they are classified into Immutable and Mutable. 🔹 Immutable String (String) An Immutable String cannot be changed after creation. Any modification creates a new object. 📌 Example: Java Copy code String s = "Hello"; s = s.concat(" World"); ✅ Features: • Cannot be modified • Creates new object on change • Stored in String Constant Pool • Memory efficient & secure 🔹 Mutable String (StringBuilder / StringBuffer) A Mutable String can be modified without creating a new object. 📌 Example: Java Copy code StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); ✅ Features: • Can be modified • Same object is updated • Faster for frequent changes • Better performance 🔹 Key Difference Immutable Mutable Cannot change Can change New object created Same object modified Uses String Uses StringBuilder / StringBuffer 🚀 Conclusion: Use String for fixed data. Use StringBuilder/StringBuffer for frequently changing data.
To view or add a comment, sign in
-
-
Hi everyone 👋 Continuing the weekend Java Keyword Series with another important keyword 👇 📌 Java Keyword Series – Part 2 ✅ super keyword in Java The super keyword is used to refer to the immediate parent class object 👇 🔹 Why do we use super? To access parent class variables To call parent class methods To call the parent class constructor 🔹 Where can we use super? 1️⃣ Access parent class variable class Parent { int x = 10; } class Child extends Parent { int x = 20; void show() { System.out.println(super.x); // prints 10 } } 2️⃣ Call parent class method class Parent { void display() { System.out.println("Parent method"); } } class Child extends Parent { void display() { super.display(); // calls parent method System.out.println("Child method"); } } 3️⃣ Call parent class constructor class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { super(); // calls parent constructor } } 🔹 In simple words super is used to access or call members of the parent class. 👉 🧠 Quick Understanding super.variable → parent variable super.method() → parent method super() → parent constructor #Java #CoreJava #JavaKeywords #LearningInPublic #BackendDevelopment
To view or add a comment, sign in
-
🕵️♂️☕ GUESS THE JAVA VERSION: CAN YOU SPOT IT? 🔸 TLDR ▪️ If you see var in Java local variables → think Java 10+ ☕🧠 🔸 THE QUIZ (GUESS BEFORE READING THE ANSWER) import java.util.*; class Example { void test() { var x = 10; var s = "hello"; var list = new ArrayList<String>(); for (var item : list) {} for (var i = 0; i < 10; i++) {} try (var r = new java.io.StringReader("")) {} } } 🔸 OPTIONS ▪️ Java 1 ▪️ Java 2 ▪️ Java 10 ▪️ Java 13 ▪️ Java 16 🔸 ANSWER ✅ Java 10 🔸 WHY? (VERY SHORT) ▪️ The giveaway is var: local-variable type inference was introduced in Java 10 (JEP 286). ▪️ You can use var for local variables, for-loop indexes, enhanced for, and try-with-resources variables (as shown here). 🔸 TAKEAWAYS ▪️ var reduces boilerplate while keeping Java statically typed ✅ ▪️ Works only for local variables (not fields / params) ▪️ Requires an initializer (no initializer = nothing to infer) ▪️ The inferred type is a real compile-time type, not “dynamic typing” #Java #Java10 #JVM #CleanCode #SoftwareEngineering #Programming #JavaDevelopers #Backend #DevTips #CodeQuality #Learning Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://lnkd.in/en7CvPmi
To view or add a comment, sign in
-
-
📌 Instance Variable vs Local Variable in Java – In Java, variables are classified based on where they are declared and how long they exist in memory. Two important types are Instance Variables and Local Variables. ✅ 1️⃣ Instance Variable in Java 👉 An instance variable is a variable declared inside a class but outside all methods. It belongs to an object (instance) of the class. 👉 Key Features: 🔹Declared inside class but outside methods 🔹Each object gets separate memory 🔹Scope is entire class 🔹Lifetime is as long as the object exists 🔹Stored in Heap memory... ✅ 2️⃣ Local Variable in Java 👉 A local variable is declared inside a method, constructor, or block. It is used only within that method or block. 👉 Key Features: 🔹Declared inside a method or block 🔹Scope is limited to that method 🔹Lifetime is only while method executes 🔹Must be initialized before use 🔹Stored in Stack memory 🔹Used for temporary calculations 🔹Used to store object properties.. Learning Java variables step by step makes OOP concepts crystal clear! Instance variables store object data, while local variables help in temporary calculations. 🙏 Special thanks to Anand Kumar Buddarapu sir for continuous guidance and support. 🙏A heartfelt thank you to Uppugundla Sairam Sir and Saketh Kallepu Sir for building such an inspiring learning environment , guidance and opportunities you provide make a huge difference in shaping our technical and professional journey. #Java #Variables #InstanceVariable #LocalVariable #JavaBasics #CodingJourney
To view or add a comment, sign in
-
-
🕵️♂️📦 GUESS THE JAVA VERSION: STATIC IMPORT EDITION 🔸 TLDR ▪️ Static imports + autoboxing → think Java 5 🧠☕ 🔸 THE QUIZ (GUESS BEFORE READING THE ANSWER) import static java.lang.System.out; import static java.util.Arrays.asList; class Example { void test() { out.println(asList(1, 2, 3)); } } 🔸 OPTIONS ▪️ Java 5 ▪️ Java 11 🔸 ANSWER ✅ Java 5 🔸 WHY? (VERY SHORT) ▪️ import static ... was introduced in Java 5. ▪️ asList(1,2,3) also leans on autoboxing (ints → Integer) which arrived in Java 5 too. 🔸 TAKEAWAYS ▪️ Static imports let you write out.println(...) instead of System.out.println(...) ▪️ asList(1, 2, 3) becomes a List<Integer> thanks to autoboxing ✅ ▪️ Use static imports sparingly: they can hide where names come from 👀 #Java #Java5 #Programming #JVM #DevTips #CleanCode #SoftwareEngineering #Backend #JavaDevelopers Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development