𝐇𝐨𝐰 𝐭𝐨 𝐑𝐞𝐚𝐝 𝐚𝐧𝐝 𝐏𝐫𝐢𝐧𝐭 𝐚𝐧 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝐕𝐚𝐥𝐮𝐞 𝐢𝐧 𝐉𝐚𝐯𝐚 𝐔𝐬𝐢𝐧𝐠 𝐒𝐜𝐚𝐧𝐧𝐞𝐫 𝐂𝐥𝐚𝐬𝐬 The Scanner class in java.util package is the easiest way to take input from the user in Java. It reads data from various input sources, including the keyboard. 𝐈𝐦𝐩𝐨𝐫𝐭 𝐃𝐞𝐜𝐥𝐚𝐫𝐚𝐭𝐢𝐨𝐧: 𝘪𝘮𝘱𝘰𝘳𝘵 𝘫𝘢𝘷𝘢.𝘶𝘵𝘪𝘭.𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝐒𝐭𝐞𝐩𝐬 𝐭𝐨 𝐑𝐞𝐚𝐝 𝐚𝐧𝐝 𝐏𝐫𝐢𝐧𝐭 𝐚𝐧 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝐮𝐬𝐢𝐧𝐠 𝐚 𝐒𝐜𝐚𝐧𝐧𝐞𝐫 ➟ Import the Scanner class. ➟ Create a Scanner object to read input. ➟ Prompt the user for input. ➟ Read the integer using nextInt(). ➟ Print the integer using System.out.println(). ▓▒░▓▒░▓▒░▓▒░▓▒░▓▒░▓▒░ 𝐄𝐱𝐚𝐦𝐩𝐥𝐞: 𝘪𝘮𝘱𝘰𝘳𝘵 𝘫𝘢𝘷𝘢.𝘶𝘵𝘪𝘭.𝘚𝘤𝘢𝘯𝘯𝘦𝘳; 𝘱𝘶𝘣𝘭𝘪𝘤 𝘤𝘭𝘢𝘴𝘴 𝘎𝘍𝘎{ 𝘱𝘶𝘣𝘭𝘪𝘤 𝘴𝘵𝘢𝘵𝘪𝘤 𝘷𝘰𝘪𝘥 𝘮𝘢𝘪𝘯(𝘚𝘵𝘳𝘪𝘯𝘨[] 𝘢𝘳𝘨𝘴){ // 𝘚𝘵𝘦𝘱 1: 𝘊𝘳𝘦𝘢𝘵𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘰𝘣𝘫𝘦𝘤𝘵 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘴𝘤 = 𝘯𝘦𝘸 𝘚𝘤𝘢𝘯𝘯𝘦𝘳(𝘚𝘺𝘴𝘵𝘦𝘮.𝘪𝘯); // 𝘚𝘵𝘦𝘱 2: 𝘗𝘳𝘰𝘮𝘱𝘵 𝘶𝘴𝘦𝘳 𝘧𝘰𝘳 𝘪𝘯𝘱𝘶𝘵 𝘚𝘺𝘴𝘵𝘦𝘮.𝘰𝘶𝘵.𝘱𝘳𝘪𝘯𝘵("𝘌𝘯𝘵𝘦𝘳 𝘢𝘯 𝘪𝘯𝘵𝘦𝘨𝘦𝘳: "); // 𝘚𝘵𝘦𝘱 3: 𝘙𝘦𝘢𝘥 𝘪𝘯𝘵𝘦𝘨𝘦𝘳 𝘪𝘯𝘱𝘶𝘵 𝘪𝘯𝘵 𝘯𝘶𝘮𝘣𝘦𝘳 = 𝘴𝘤.𝘯𝘦𝘹𝘵𝘐𝘯𝘵(); // 𝘚𝘵𝘦𝘱 4: 𝘗𝘳𝘪𝘯𝘵 𝘵𝘩𝘦 𝘦𝘯𝘵𝘦𝘳𝘦𝘥 𝘪𝘯𝘵𝘦𝘨𝘦𝘳 𝘚𝘺𝘴𝘵𝘦𝘮.𝘰𝘶𝘵.𝘱𝘳𝘪𝘯𝘵𝘭𝘯("𝘠𝘰𝘶 𝘦𝘯𝘵𝘦𝘳𝘦𝘥: " + 𝘯𝘶𝘮𝘣𝘦𝘳); // 𝘊𝘭𝘰𝘴𝘦 𝘵𝘩𝘦 𝘴𝘤𝘢𝘯𝘯𝘦𝘳 𝘴𝘤.𝘤𝘭𝘰𝘴𝘦(); } } ▓▒░▓▒░▓▒░▓▒░▓▒░▓▒░▓▒░▓▒░ 𝐎𝐮𝐭𝐩𝐮𝐭: Enter an integer: 123 You entered: 123 ...Program finished with exit code 0 Press ENTER to exit console. 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧: ➟ Scanner sc = new Scanner(System.in); -> Creates a Scanner object to take input. ➟ nextInt() -> Reads an integer value entered by the user. ➟ System.out.println() -> Prints the entered integer on the screen. #Java #PrintanInteger #ScannerClass #String #JAVAEXPLANATIONS #JAVAExamples #Coding #Developer #CodeLife #Programmer #AshokIT
Java Scanner Class for Reading and Printing an Integer
More Relevant Posts
-
𝐀𝐬 𝐝𝐞𝐯𝐞𝐥𝐨𝐩𝐞𝐫𝐬, 𝐰𝐞 𝐝𝐨𝐧’𝐭 𝐣𝐮𝐬𝐭 𝐰𝐫𝐢𝐭𝐞 𝐜𝐨𝐝𝐞. 𝐖𝐞 𝐦𝐮𝐬𝐭 𝐮𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝 𝐰𝐡𝐚𝐭 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐛𝐞𝐡𝐢𝐧𝐝 𝐭𝐡𝐞 𝐬𝐜𝐞𝐧𝐞𝐬. == vs .equals() in Java. At first glance, they look similar. But they check completely different things. == ------->Compares references (memory location) .equals() ----->Compares actual content Example: String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println(s1 == s2); // true System.out.println(s1 == s3); // false System.out.println(s1.equals(s3)); // true Why? ✔ s1 and s2 point to the same object in the String Constant Pool ✔ s3 creates a new object in the heap ✔ .equals() checks character-by-character content(not the reference) This small difference can cause BIG bugs, especially when working with Strings, Objects, or Collections. Understanding memory behavior > Memorizing syntax. #Java #Programming #LearningInPublic #dailyChallenge
To view or add a comment, sign in
-
𝐃𝐚𝐲 𝟗 – 𝐑𝐞𝐯𝐢𝐬𝐢𝐭𝐢𝐧𝐠 𝟐-𝐃 𝐀𝐫𝐫𝐚𝐲𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚 One important realization: 👉 In Java, a 2-D array is NOT actually a “matrix”. It is an array of arrays. That means: Each row is a separate array object. Rows can have different lengths. Memory is not necessarily continuous like in C/C++ Example: int[][] arr = new int[3][]; arr[0] = new int[2]; arr[1] = new int[4]; arr[2] = new int[3]; This is called a 𝑱𝒂𝒈𝒈𝒆𝒅 𝑨𝒓𝒓𝒂𝒚. Many beginners assume: arr.length == total elements ❌ But actually: arr.length → number of rows arr[i].length → number of columns in that specific row This small understanding prevents many traversal bugs. The deeper you understand memory structure, the cleaner your logic becomes. 🔹 Beginner Level 2-D Array Problems : These are simple but build strong fundamentals. 1️⃣ Print a 2D array----> Traverse and print all elements. 2️⃣ Find the sum of all elements 3️⃣ Row-wise sum-----> Print sum of each row separately. 4️⃣ Column-wise sum---->This helps understand traversal direction change. 5️⃣ Find the largest element----> Simple scanning problem. #Java #DataStructures #LearningInPublic #dailyChallenge
To view or add a comment, sign in
-
🚨 Most Java performance issues start with ONE wrong choice. String. StringBuffer. StringBuilder. They look similar… but behave very differently under the hood. This visual breaks it down without code overload, so you can choose right every time 👇 🔹 String — Immutable by Design ✔ Thread-safe by default ✔ Secure & predictable ❌ Creates new objects on every modification 📌 Best for: constants, read-only values ⚠️ Avoid when strings change frequently (loops, concatenation) 🔹 StringBuffer — Mutable + Thread-Safe ✔ Safe in multithreaded environments ✔ Synchronized internally ❌ Slower due to locking overhead 📌 Best for: legacy or concurrent environments where safety > speed 🔹 StringBuilder — Mutable + Fast ✔ Fastest for string operations ✔ No synchronization overhead ❌ Not thread-safe 📌 Best for: single-threaded logic, loops, data processing 🧠 One Line That Wins Interviews String is immutable. StringBuffer is synchronized. StringBuilder is fast. Choose based on: 🔒 Immutability 🧵 Thread safety ⚡ Performance 📌 Pro Tip: If you’re doing string concatenation inside a loop and using String… you’re silently creating performance debt. 💬 Interview question for you: 👉 When would you intentionally choose StringBuffer over StringBuilder? Drop your answer below 👇 Save this for revision ⭐ Share it with someone preparing for Java interviews 🔁 #Java #String #StringBuilder #StringBuffer #JavaInterview #BackendDevelopment #PerformanceOptimization #CleanCode #SoftwareEngineering #SpringBoot
To view or add a comment, sign in
-
-
❌ == is NOT the same as equals() in java They look similar, but they answer two different questions. 🔸== operator Checks reference equality ➡️ Do both variables point to the same object? 🔸equals() method Checks logical equality ➡️ Do both the objects have same value/content? ☘️ Example String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false (different objects) System.out.println(a.equals(b)); // true (same content) Even though the text is the same, a and b are stored at different memory locations. 💡Thumb Rule 🔸Use == for primitive types (int, double, boolean) 🔸Use equals for objects (String, custom classes) Getting this wrong can cause subtle bugs, especially when comparing Strings. #Java #SoftwareEngineering #Cleancode #Programming
To view or add a comment, sign in
-
-
Day 18 : looping statement A statements are used to execute some set of instructions repeatedly is called a looping statement. we can iterate loop desired number of time based on requirement. In java 4 types of loops 1.for loop 2.while loop 3. do-while loop 4.for each loop or enhance for loop loops has 3 part ie. initialization, condition , updation. for each loop doesn't contain this parts. for loop: A statements are used to execute some set of instructions repeatedly. used when we know the number of iterations. In this loop first we initialize a variable then give a condition and the updation statement if we doens't specify the condition by default jvm adds true then loop goes infinite. Syntax. for(initialization; Condition; updation){ // Statement } ex. for(int i=1;i<=10;i++){ s.o.p(i); } while loop: used to execute some set of instructions repeatedly. We use while loop when we don’t know the number of iterations Initialization, condition and updation are not declared at the same line. It throws a compile time error if we are not specifying the condition. syntax: initialization; while(condition){ // statements; updation; } ex. int a =1; while(a<=10){ s.o.p("hello "+a); a++; } #corejava #java #loop #forloop #whileloop
To view or add a comment, sign in
-
-
📄Java clone() 1️⃣ What clone means Shallow copy → copy the Object reference Deep copy → copy the Object reference+ copy their fields deeply 2️⃣ What Java actually does by default super.clone() ➡ Copies object structure ➡ Inner objects are shared So Java clone copies: ✔ primitives ❌ references (pointer copied, not object) 3️⃣ How we make it Deep Copy Manually clone inner objects: new Location(this.location) So: super.clone() + manual cloning = Deep Copy 4️⃣ Return Type Confusion Java forces method signature: Object clone() Compiler only sees Object So we cast: User copy = (User) original.clone(); 🧠 Casting does NOT create or convert objects It only changes how compiler views the reference 5️⃣ What actually happens internally clone() → memory duplication (no constructor called) Casting → only permission to access methods Object ref = userClone; ((User)ref).getName(); // allowed after cast No new object created here. 6️⃣ Important internal fact clone() in Object is a native method Real implementation exists inside JVM (C/C++), so IDE cannot open its source code. return (User) super.clone(); → works, but only shallow copy return new User(this); → works and can be deep copy GitHub Link: https://lnkd.in/g5Zj48m6 🔖Frontlines EduTech (FLM) #java #coreJava #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #cloneMethod #deepCopy #shallowCopy
To view or add a comment, sign in
-
-
#Coding10 👉 Q: Remove Duplicates from a Sorted Array (Two Pointer Technique – Java). Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 ✅ Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; // pointer for next unique position for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j] = arr[i]; j++; } } return j; // number of unique elements } How It Works Since the array is already sorted, duplicates are adjacent i scans the array j tracks the position to place the next unique element When a new element is found → place it at index j Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) Two-pointer pattern is extremely powerful for array problems. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
Difference between equals() method and == operator in Java This is one of the most commonly asked Java questions, yet many developers still get confused in real projects. Let’s simplify it 👇 ✅ == (Equality Operator) - Compares memory references - Checks whether both variables point to the same object - Works for primitive types by comparing actual values String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false 👉 Because a and b point to different objects in memory ✅ equals() (Method) - Compares content / logical equality - Behavior depends on class implementation - Many Java classes (String, Integer, etc.) override equals() System.out.println(a.equals(b)); // true 👉 Because both strings contain the same value 🧠 Key Difference (One-liner) ⚠️ Real-World Tip If you create custom classes, always override: - equals() - hashCode() Otherwise, collections like HashSet and HashMap may behave incorrectly. #Java #JavaInterview #Programming #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
🔹 Discussion Topic: Why For-Each Loop Cannot Modify Elements 💬 Discussion Topic: Understanding how for-each works under the hood and why it’s read-only for primitives Imagine iterating over arrays or collections in a Java program: You want to traverse elements quickly You might expect to modify values directly during iteration 🔹 How For-Each Works Automatically iterates over arrays or any Iterable collection For primitives, the loop variable stores a copy of the element For objects, the loop variable stores a reference to the object Internally uses index-based access for arrays and Iterator for collections 🔹 Why Modification Doesn’t Work Primitives: Changing the loop variable modifies only the copy, not the original element Objects: You can change the state of the object, but you cannot replace the object itself in the array or collection References: Reassigning the loop variable affects only the temporary reference, leaving the collection unchanged ❌ Cannot directly modify array elements or collection elements ❌ Cannot delete or replace elements ✅ Correct Approach For modifying primitives in arrays → use index-based loops For modifying or deleting elements in collections → use Iterator methods 💡 Pro Tip: Use for-each for reading/traversing only Always remember the difference between copy vs reference This knowledge prevents subtle bugs in production code
To view or add a comment, sign in
-
-
🔹 Java String Concept – Reverse a String using Char Array 👉 Concept: A string can be reversed by converting it into a char array and swapping characters from the beginning and end. Steps: 1. Convert string into char array using toCharArray(). 2. Run loop till half length. 3. Swap first and last characters. 4. Convert char array back to string. Code: String str = "Mohan is there"; char[] charArray = str.toCharArray(); for(int i = 0; i < charArray.length/2; i++){ char temp = charArray[i]; charArray[i] = charArray[charArray.length-1-i]; charArray[charArray.length-1-i] = temp; } System.out.println(new String(charArray)); 👉 Output: ereht si nahoM 🧠 What I learned: • String to char array conversion • Loop logic • Swapping concept • Problem solving approach #java #StringConcepts #CodingJourney #JavaDeveloper #LearningInPublic
To view or add a comment, sign in
-
More from this author
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