[Go to site: main page, start]

0% found this document useful (0 votes)
2 views17 pages

Basic Java

This document serves as a beginner's guide to Java programming, covering essential topics such as Java's definition, history, features, installation, and the creation of a simple 'Hello World' program. It emphasizes Java's popularity due to its cross-platform capabilities and provides step-by-step instructions for setting up the Java Development Kit (JDK) and an Integrated Development Environment (IDE). Additionally, it introduces key concepts like object-oriented programming and important interview questions related to Java.

Uploaded by

ravivish5616
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Basic Java

This document serves as a beginner's guide to Java programming, covering essential topics such as Java's definition, history, features, installation, and the creation of a simple 'Hello World' program. It emphasizes Java's popularity due to its cross-platform capabilities and provides step-by-step instructions for setting up the Java Development Kit (JDK) and an Integrated Development Environment (IDE). Additionally, it introduces key concepts like object-oriented programming and important interview questions related to Java.

Uploaded by

ravivish5616
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Namaste, future Java developer!

👋 I'm super excited to be your guide on this amazing journey


into the world of programming with Java. Don't worry if you're completely new to this; we'll start
from the very basics, aur main aapko sab kuch itna simple tarike se samjhaunga jaise koi dost
samjhata hai.

Table of Contents
1.​ What is Java?
2.​ History and Features of Java
3.​ Installation and Setup
4.​ Hello World Program
5.​ Variables and Data Types
6.​ Operators
7.​ Input/Output in Java
8.​ Conditional Statements (if, if-else, switch)
9.​ Loops (for, while, do-while)
10.​Arrays
11.​Object-Oriented Programming Concepts (OOP)
12.​Classes and Objects
13.​Inheritance
14.​Polymorphism
15.​Abstraction and Encapsulation
16.​Constructors
17.​Static and Final Keywords
18.​String Handling
19.​Exception Handling
20.​File Handling (basic)
21.​Java Collections (basic intro)
Let's begin our first lesson!

1. What is Java?
Introduction

So, pehle hum yeh samjhte hain ki Java kya hai? Java ek bahut popular programming
language hai aur ek computing platform bhi hai. Simple terms mein, Java ek tareeke ki bhasha
hai jise hum computer ko instructions dene ke liye use karte hain. Jaise hum insaan ek doosre
se baat karne ke liye Hindi, English ya koi aur bhasha use karte hain, waise hi hum computers
se baat karne ke liye programming languages use karte hain.

Real-world Comparison

Imagine karo ki aap ek restaurant mein ho. Aap waiter ko batate ho ki aapko kya khana hai,
jaise "Mujhe ek Masala Dosa chahiye." Yahan par aapki language (Hindi/English) instruction
dene ka kaam kar rahi hai. Similarly, Java computer ko instructions deti hai ki kya karna hai.
Jaise aapka order kitchen mein banega, waise hi Java code compile (process) hokar computer
mein run hota hai.
Why is Java so popular?

Java is popular because it's cross-platform. Iska matlab hai ki jo code aap ek computer par
likhte ho, woh doosre computer par bhi chal jayega bina kisi bade change ke. Isko Java ki
tagline mein bolte hain: "Write Once, Run Anywhere (WORA)". Jaise ek USB drive kisi bhi
computer mein lag jati hai, waise hi Java code kisi bhi operating system (Windows, macOS,
Linux) par chal sakta hai.

Important Interview Question (for future use)

●​ Q: What is the "Write Once, Run Anywhere" (WORA) principle in Java?


○​ A: It means that Java code compiled on one platform (like Windows) can be run on
any other platform (like macOS or Linux) without needing to be recompiled. This is
possible due to the Java Virtual Machine (JVM).

2. History and Features of Java


Introduction

Har cheez ki tarah, Java ki bhi ek kahani hai. Chalo, dekhte hain ki Java kaise bani aur ismein
kya khaas baatein hain.

History of Java

Java ko James Gosling aur uski team ne Sun Microsystems (ab Oracle ka part hai) mein
develop kiya tha mid-1990s mein. Initially, iska naam "Oak" tha, phir "Green" hua, aur finally
"Java" rakha gaya. Iska pehla stable release JDK 1.0 tha 1996 mein. Pehle isko consumer
electronic devices ke liye banaya gaya tha, but internet ke boom ke saath, yeh web applications
ke liye popular ho gayi.

Features of Java

Java mein bahut saari khaas baatein hain jo isko itna powerful banati hain:
●​ Simple: Java ko design hi is tarah se kiya gaya hai ki yeh C++ se bhi zyada simple aur
easy to learn ho. Agar aapko C++ ki basic understanding hai, toh Java aapko aur bhi
easy lagegi.
●​ Object-Oriented: Java mein sab kuch Objects ke around ghoomta hai. Isse code
organize karna aur maintain karna easy ho jaata hai. Hum iske baare mein aage detail
mein padhenge.
●​ Platform Independent: Jaise humne pehle baat ki, "Write Once, Run Anywhere". Yeh
Java ki sabse badi khoobi hai. Aap ek OS par code likho, woh dusre OS par bhi chalega.
Iska raaz hai JVM (Java Virtual Machine).
○​ Diagram:​
+-------------------+ +-----------------+
+-----------------+​
| Java Source | | Java Bytecode | |
Java Program |​
| (.java file) | ----> | (.class file) | ----> |
Runs on JVM |​
+-------------------+ +-----------------+
+-----------------+​
(Compiler) (JVM)​

●​ Secure: Java mein security features built-in hain. Ismein virus ya tampering se bachne ke
liye mechanisms hain. Aap Java applications par trust kar sakte ho.
●​ Robust: "Robust" ka matlab hota hai strong and reliable. Java mein strong memory
management hai aur yeh error handling ko bhi support karta hai, jisse programs crash
hone se bach jaate hain.
●​ Multithreaded: Multithreading ka matlab hai ki aap ek hi program mein ek saath kai tasks
perform kar sakte ho. Jaise aap gaana sunte hue typing kar rahe ho, waise hi Java
program bhi ek saath kai kaam kar sakta hai.
●​ High Performance: Java bytecode high performance deta hai kyunki isko JIT (Just In
Time) compiler use karta hai jo bytecode ko native machine code mein convert karta hai
runtime par.
●​ Distributed: Java ko distributed applications banane ke liye design kiya gaya hai. Iska
matlab hai ki programs internet par network mein distribute kiye ja sakte hain.
●​ Dynamic: Java dynamic hai. Iska matlab hai ki Java programs mein information runtime
par adapt ho sakti hai. Yeh new classes, objects, aur libraries ko dynamically load kar
sakta hai.

Important Interview Question

●​ Q: Name some key features of Java.


○​ A: Object-Oriented, Platform Independent, Simple, Secure, Robust, Multithreaded,
High Performance, Distributed, Dynamic.

3. Installation and Setup


Introduction

Ab humne Java ke baare mein thoda bahut jaan liya hai, toh ab time hai isko apne computer
mein setup karne ka. Programming karne ke liye humein kuch tools ki zaroorat padegi.

What we need:

1.​ JDK (Java Development Kit): Yeh woh kit hai jismein Java ko develop karne ke liye
saare tools hote hain, jaise compiler (jo aapke likhe code ko computer ke samajhne wali
language mein badalta hai) aur JRE (Java Runtime Environment - jo Java programs ko
run karta hai).
2.​ An IDE (Integrated Development Environment) or a Text Editor: Jahan hum apna
Java code likhenge. Beginners ke liye, ek simple text editor (jaise Notepad++, Sublime
Text, VS Code) bhi chalega, ya phir ek beginner-friendly IDE jaise IntelliJ IDEA
Community Edition ya Eclipse. Hum IDE use karenge kyunki woh bahut saari cheezein
automatically handle kar leta hai aur debugging mein help karta hai.
Steps to Install JDK:

Step 1: Download JDK


●​ Go to the official Oracle website for Java downloads: search on Google for "Oracle JDK
download".
●​ Look for the latest LTS (Long Term Support) version. For example, if Java 17 is the
latest LTS, download that.
●​ Choose the correct installer for your operating system (Windows, macOS, Linux).
Step 2: Run the Installer
●​ Download hone ke baad, installer file par double-click karo.
●​ Follow the on-screen instructions. Zyada kuch change karne ki zaroorat nahi hai, just click
"Next" or "Install".
●​ By default, JDK usually installs in a location like C:\Program Files\Java\jdk-xx.x (for
Windows).
Step 3: Set Environment Variables (Crucial Step!)
●​ Yeh step thoda technical hai, but bahut important hai. Isse aapka operating system jaan
jayega ki Java kahan install hua hai.
●​ For Windows:
1.​ Search for "Environment Variables" in the Windows search bar and click on "Edit
the system environment variables".
2.​ Click on the "Environment Variables..." button.
3.​ Under "System variables", find a variable named Path. Select it and click "Edit...".
4.​ Click "New" and add the path to your JDK's bin directory. For example, if your JDK
is installed at C:\Program Files\Java\jdk-17, then you need to add C:\Program
Files\Java\jdk-17\bin.
5.​ Click "OK" on all windows to save the changes.
6.​ Verify installation: Open Command Prompt (CMD) and type java -version. Agar
aapko Java version dikh jaye, toh installation successful hai! Also, type javac
-version to check the Java compiler.
●​ For macOS/Linux:
○​ This usually involves editing your shell profile file (like .bash_profile, .zshrc, or
.bashrc) and adding the JDK bin path to the PATH variable. A simple web search for
"set java path mac" or "set java path linux" will give you precise instructions for your
specific setup.
○​ Verify installation: Open Terminal and type java -version and javac -version.

Recommended IDE: IntelliJ IDEA Community Edition

●​ Download IntelliJ IDEA Community Edition from the JetBrains website. This is a free
version and excellent for beginners.
●​ Install it by following the on-screen instructions. It's quite straightforward.
●​ Once installed, open IntelliJ IDEA. It will guide you through creating your first Java project.

Mini Practice Problem

●​ P: Check if Java is correctly installed on your system using the command


prompt/terminal.
○​ Hint: Use java -version and javac -version.

Important Interview Question

●​ Q: What is the difference between JDK, JRE, and JVM?


○​ A:
■​ JDK (Java Development Kit): It's a software development environment used
for developing Java applications and applets. It includes the JRE and tools
like the compiler (javac) and debugger. Yeh woh poora kit hai jismein Java
code likhne aur chalane ke liye sab kuch hai.
■​ JRE (Java Runtime Environment): It's a set of software tools that enables
the execution of Java applications. It provides the minimum requirements for
executing a Java application. It contains the JVM and core classes. Yeh sirf
Java applications ko run karne ke liye hai.
■​ JVM (Java Virtual Machine): It's an abstract machine that provides a
runtime environment in which Java bytecode can be executed. It's the core of
the Java platform's "Write Once, Run Anywhere" capability. Yeh woh machine
hai jo aapke Java code ko chalaati hai.

4. Hello World Program


Introduction

Har programming language mein, "Hello World" program sabse pehla program hota hai jo hum
likhte hain. Yeh ek chota sa program hai jo screen par "Hello, World!" print karta hai. Isse hum
programming ki basic structure aur compilation/execution process ko samajhte hain.

Real-world Comparison

Imagine karo ki aapne abhi-abhi ek nayi bhasha seekhni shuru ki hai, jaise French. Toh aapka
pehla word ya phrase kya hoga? Shayad "Bonjour!" ya "Hello!". Waise hi, programming ki
duniya mein, "Hello World" hamara pehla kadam hai.

Syntax

Java mein "Hello World" program kuch aisa dikhta hai:


public class HelloWorld {​
public static void main(String[] args) {​
[Link]("Hello, World!");​
}​
}​

Let's break it down line by line, jaise ek-ek ingredient samjhte hain:
●​ public class HelloWorld { ... }:
○​ class: Java mein, har code classes ke andar likha jaata hai. Class ek blueprint ki
tarah hai.
○​ HelloWorld: Yeh hamari class ka naam hai. Aap apni marzi se koi bhi naam de
sakte ho, but convention hai ki class ka naam capital letter se start ho.
○​ public: Iska matlab hai ki yeh class kahin se bhi access ki ja sakti hai. Don't worry
too much about public right now, bas itna samjho ki yeh ek access specifier hai.
●​ public static void main(String[] args) { ... }:
○​ Yeh line bahut important hai! Yeh ek special method hai jahan se aapka Java
program execute (run) hona start hota hai. Computer sabse pehle isi line ko
dhundhta hai.
○​ public: Jaise upar dekha, access specifier.
○​ static: Iska matlab hai ki aap is method ko bina class ka object banaye run kar
sakte ho. Don't stress too much here.
○​ void: Iska matlab hai ki yeh method kuch bhi return nahi karegi.
○​ main: Yeh method ka naam hai. Always main for the starting point.
○​ (String[] args): Yeh method ke parameters hain. Iska matlab hai ki main method
command line arguments (extra information) accept kar sakti hai. Abhi ke liye, bas
itna samjho ki yeh har main method mein likha jaata hai.
●​ [Link]("Hello, World!");:
○​ Yeh woh line hai jo actual mein "Hello, World!" screen par print karti hai.
○​ System: Ek built-in Java class hai jo system resources (jaise output screen) ko
access karti hai.
○​ out: System class ke andar ek object hai jo standard output stream ko represent
karta hai (usually aapki screen).
○​ println: Yeh out object ka ek method hai jo text ko print karta hai aur ek nayi line bhi
start karta hai (print ln = print line).
○​ "Hello, World!": Yeh woh text hai jo hum print karwana chahte hain. Jo bhi double
quotes "" ke andar hota hai, woh as it is print ho jaata hai.
○​ ;: Har statement Java mein semicolon ; se end hoti hai. Jaise Hindi mein . ya
English mein full stop.

Sample Java Program with Output

1. Using a Text Editor (like Notepad/VS Code):


●​ Open Notepad or any text editor.
●​ Type the exact code given above.
●​ Save the file as [Link]. Make sure the file name is exactly the same as the class
name and ends with .java.
●​ Open Command Prompt (CMD) or Terminal.
●​ Navigate to the directory where you saved your file. (Example: cd
C:\Users\YourName\Documents)
●​ Compile the program: Type javac [Link] and press Enter.
○​ Agar koi error nahi aaya, toh [Link] naam ki ek file ban jayegi usi
directory mein. Yeh file bytecode hai.
●​ Run the program: Type java HelloWorld and press Enter.
●​ Output:​
Hello, World!​

2. Using IntelliJ IDEA:


●​ Open IntelliJ IDEA.
●​ Click on "New Project".
●​ Give a name to your project (e.g., MyFirstJavaProject).
●​ Select "Java" as the language and choose your installed JDK.
●​ Click "Create".
●​ In the project structure, navigate to src folder (source folder).
●​ Right-click on src, then select New -> Java Class.
●​ Give the class name as HelloWorld and press Enter.
●​ IntelliJ will automatically create a basic class structure.
●​ Copy-paste or type the "Hello World" code inside the HelloWorld class.
●​ Click on the green "Run" arrow next to the main method, or go to Run -> Run 'HelloWorld'.
●​ You will see the output in the "Run" window at the bottom of the IDE.

Mini Practice Problem

●​ P: Modify the "Hello World" program to print your name instead of "Hello, World!". For
example, "Hello, [Your Name]!".
●​ P: Try to remove the semicolon at the end of [Link] line and see what error
you get. This will help you understand the importance of semicolons.

Important Interview Question

●​ Q: Explain the purpose of the main method in a Java program.


○​ A: The main method is the entry point for any Java application. When you run a
Java program, the Java Virtual Machine (JVM) looks for and executes this main
method first. Without a main method, a Java application cannot be executed.

5. Variables and Data Types


Introduction

Jab hum koi program banate hain, toh humein data store karna padta hai. Jaise aapke paas ek
notebook hoti hai jismein aap kuch numbers ya names likhte ho, waise hi programming mein
hum variables ka use karte hain data ko store karne ke liye.

Real-world Comparison

Ek variable ko aap ek container ya ek box ki tarah samajh sakte ho. Har box ka ek naam hota
hai aur uske andar aap kuch specific type ki cheez hi rakh sakte ho. Jaise ek sugar box mein
aap sugar hi rakhoge, pani nahi. Similarly, programming mein, ek variable ka ek naam hota hai
aur woh ek specific type ka data hi store kar sakta hai.

What are Variables?

Variables are basically named memory locations. Jab aap ek variable banate ho, toh computer
memory mein ek jagah reserve ho jaati hai us data ko store karne ke liye, aur us jagah ko aap
us variable ke naam se refer kar sakte ho.

Syntax for Declaring Variables

dataType variableName = value;​


●​ dataType: Yeh batata hai ki variable kis type ka data store karega (jaise number, text,
decimal number, etc.).
●​ variableName: Yeh variable ka naam hai, jisse hum us data ko access karenge.
●​ =: Yeh assignment operator hai, jo value ko variableName mein store karta hai.
●​ value: Woh actual data jo aap store karna chahte ho.

Data Types in Java

Java mein do main categories ke data types hote hain:


1.​ Primitive Data Types: Yeh basic data types hain jo single values store karte hain.
○​ Integers (whole numbers):
■​ byte: Smallest integer, stores numbers from -128 to 127. (Bada chhota
dabba)
■​ short: A bit larger, -32,768 to 32,767. (Thoda bada dabba)
■​ int: Most commonly used for whole numbers. Stores numbers from approx. -2
billion to 2 billion. (Standard dabba)
■​ long: For very large whole numbers. (Bahut bada dabba)
○​ Floating-point numbers (decimal numbers):
■​ float: Stores numbers with decimals (e.g., 3.14f). f ya F suffix lagana padta
hai.
■​ double: More precise, commonly used for decimal numbers. (Zyada use hota
hai)
○​ Characters:
■​ char: Stores a single character (e.g., 'A', '7', '$'). Single quotes ' ' mein aata
hai.
○​ Boolean:
■​ boolean: Stores only two values: true or false. Yeh conditions check karne ke
liye use hota hai. (Haan ya Naa)
2.​ Non-Primitive (Reference) Data Types: Yeh complex data types hote hain aur objects
ko refer karte hain. Examples include String, Arrays, Classes, Interfaces. Hum inke baare
mein aage detail mein padhenge. Abhi ke liye, String ko dekhte hain.
○​ String: Stores a sequence of characters (text). Double quotes "" mein aata hai.

Examples of Variable Declaration and Initialization

public class VariableExamples {​


public static void main(String[] args) {​
// Integer variables​
int age = 25; // An integer variable named 'age' storing value
25​
long bigNumber = 1234567890123L; // 'L' or 'l' for long
literals​

// Floating-point variables​
float temperature = 98.6f; // 'f' or 'F' for float literals​
double pi = 3.1415926535;​

// Character variable​
char grade = 'A'; // Single character in single quotes​

// Boolean variable​
boolean isJavaFun = true; // Stores true or false​

// String variable (Non-primitive)​
String name = "Anuj Sharma"; // Text in double quotes​

// Printing the values of variables​
[Link]("My age is: " + age);​
[Link]("A very big number: " + bigNumber);​
[Link]("Current temperature: " + temperature);​
[Link]("Value of PI: " + pi);​
[Link]("My grade is: " + grade);​
[Link]("Is Java fun? " + isJavaFun);​
[Link]("My name is: " + name);​

// Reassigning a variable (changing its value)​
age = 26; // Age is now 26​
[Link]("My new age is: " + age);​
}​
}​

Output:

My age is: 25​


A very big number: 1234567890123​
Current temperature: 98.6​
Value of PI: 3.1415926535​
My grade is: A​
Is Java fun? true​
My name is: Anuj Sharma​
My new age is: 26​

Explanation of the + operator with [Link]

Yahan + operator strings ko jod raha hai (concatenation). Jab aap String aur kisi variable ko +
se join karte ho, toh variable ki value string mein convert ho jaati hai aur print ho jaati hai. Jaise,
"My age is: " + age becomes "My age is: 25".

Mini Practice Problems

●​ P: Declare two variables, one int named itemPrice and one double named discount.
Assign them appropriate values (e.g., itemPrice = 100, discount = 0.15). Print both values.
●​ P: Create a char variable named initial and assign your first name's initial to it. Then print
it with a message like "My initial is: ".
●​ P: Try to assign a decimal value (e.g., 3.5) to an int variable and see what error Java
gives you. Why does it happen?

Important Interview Questions

●​ Q: What is a variable in Java?


○​ A: A variable is a named memory location used to store data. It has a specific data
type, which determines the type of values it can hold.
●​ Q: Differentiate between primitive and non-primitive data types in Java.
○​ A:
■​ Primitive data types: These are basic data types that store direct values.
They have a fixed size and are pre-defined by Java. Examples: int, char,
boolean, float, double, byte, short, long.
■​ Non-primitive data types (or Reference data types): These do not store
the direct value but rather references (addresses) to objects. Their size is not
fixed. Examples: String, Arrays, Classes, Interfaces.
●​ Q: What is the default value of an int variable and a boolean variable if not explicitly
initialized?
○​ A: For int, the default value is 0. For boolean, the default value is false. (Note: This
is true for instance variables and static variables. Local variables (inside
methods) must be explicitly initialized before use, otherwise, you'll get a
compile-time error.)

6. Operators
Introduction

Operators special symbols hote hain jo variables aur values par operations perform karte hain.
Jaise math mein +, -, *, / hote hain, waise hi programming mein bhi operators hote hain.

Real-world Comparison

Imagine karo ki aapke paas kuch ingredients hain (variables), aur aapko unse kuch banana hai
(operation). Toh aap knife (cutting operator), spoon (mixing operator), ya stove (heating
operator) use karte ho. Operators bhi Java mein aise hi kaam karte hain, woh values ko
manipulate karte hain.

Types of Operators in Java

Java mein kai tarah ke operators hote hain:


1.​ Arithmetic Operators: Basic math operations ke liye.
○​ + (Addition): Add karta hai.
○​ - (Subtraction): Subtract karta hai.
○​ * (Multiplication): Multiply karta hai.
○​ / (Division): Divide karta hai. Integer division mein decimal part hat jaata hai (5 / 2
will be 2).
○​ % (Modulus): Remainder deta hai division ke baad (5 % 2 will be 1).
○​ ++ (Increment): Value ko 1 se badhata hai (x++ ya ++x).
○​ -- (Decrement): Value ko 1 se ghataata hai (x-- ya --x).
2.​ Assignment Operators: Values ko variables mein assign karne ke liye.
○​ = (Assignment): Assign karta hai value. (e.g., x = 10;)
○​ +=, -=, *=, /=, %=: Shorthand operators. (e.g., x += 5; is same as x = x + 5;)
3.​ Comparison (Relational) Operators: Do values ko compare karne ke liye. Result always
boolean (true or false) hota hai.
○​ == (Equal to): Check karta hai ki do values equal hain ya nahi.
○​ != (Not equal to): Check karta hai ki do values equal nahi hain.
○​ > (Greater than): Check karta hai pehli value doosri se badi hai.
○​ < (Less than): Check karta hai pehli value doosri se chhoti hai.
○​ >= (Greater than or equal to): Check karta hai pehli value doosri se badi ya barabar
hai.
○​ <= (Less than or equal to): Check karta hai pehli value doosri se chhoti ya barabar
hai.
4.​ Logical Operators: Multiple conditions ko combine karne ke liye. Result boolean hota
hai.
○​ && (Logical AND): true agar both conditions true hon. (A aur B dono sahi honge
toh hi kaam hoga)
○​ || (Logical OR): true agar at least one condition true ho. (A ya B mein se koi bhi
sahi ho, kaam ho jayega)
○​ ! (Logical NOT): Condition ko reverse karta hai (true ko false aur false ko true).
5.​ Bitwise Operators: Bits par operations perform karne ke liye. (Advanced topic, abhi ke
liye skip kar sakte ho).

Sample Java Program with Output

public class OperatorsExample {​


public static void main(String[] args) {​
// Arithmetic Operators​
int a = 10;​
int b = 3;​
[Link]("--- Arithmetic Operators ---");​
[Link]("a + b = " + (a + b)); // Output: 13​
[Link]("a - b = " + (a - b)); // Output: 7​
[Link]("a * b = " + (a * b)); // Output: 30​
[Link]("a / b = " + (a / b)); // Output: 3
(Integer division)​
[Link]("a % b = " + (a % b)); // Output: 1
(Remainder)​

// Increment and Decrement​
int x = 5;​
[Link]("Initial x: " + x); // Output: 5​
x++; // x becomes 6 (post-increment)​
[Link]("x after x++: " + x); // Output: 6​
++x; // x becomes 7 (pre-increment)​
[Link]("x after ++x: " + x); // Output: 7​

int y = 10;​
[Link]("Initial y: " + y); // Output: 10​
y--; // y becomes 9 (post-decrement)​
[Link]("y after y--: " + y); // Output: 9​
--y; // y becomes 8 (pre-decrement)​
[Link]("y after --y: " + y); // Output: 8​

// Assignment Operators​
int c = 10;​
[Link]("--- Assignment Operators ---");​
c += 5; // c = c + 5; => c = 15​
[Link]("c after c += 5: " + c); // Output: 15​
c *= 2; // c = c * 2; => c = 30​
[Link]("c after c *= 2: " + c); // Output: 30​

// Comparison Operators​
int p = 7;​
int q = 5;​
[Link]("--- Comparison Operators ---");​
[Link]("p == q: " + (p == q)); // Output: false​
[Link]("p != q: " + (p != q)); // Output: true​
[Link]("p > q: " + (p > q)); // Output: true​
[Link]("p <= q: " + (p <= q)); // Output: false​

// Logical Operators​
boolean isSunny = true;​
boolean isWeekend = false;​
[Link]("--- Logical Operators ---");​
[Link]("isSunny && isWeekend: " + (isSunny &&
isWeekend)); // Output: false (true AND false = false)​
[Link]("isSunny || isWeekend: " + (isSunny ||
isWeekend)); // Output: true (true OR false = true)​
[Link]("!isSunny: " + (!isSunny));
// Output: false (NOT true = false)​
}​
}​

Output:

--- Arithmetic Operators ---​


a + b = 13​
a - b = 7​
a * b = 30​
a / b = 3​
a % b = 1​
Initial x: 5​
x after x++: 6​
x after ++x: 7​
Initial y: 10​
y after y--: 9​
y after --y: 8​
--- Assignment Operators ---​
c after c += 5: 15​
c after c *= 2: 30​
--- Comparison Operators ---​
p == q: false​
p != q: true​
p > q: true​
p <= q: false​
--- Logical Operators ---​
isSunny && isWeekend: false​
isSunny || isWeekend: true​
!isSunny: false​

Mini Practice Problems

●​ P: Calculate the area of a rectangle. Declare two integer variables, length = 15 and width
= 8. Use the multiplication operator to find the area and print it.
●​ P: Check if a person is eligible to vote. Declare an int variable personAge = 17 and a
boolean variable isEligible. Use a comparison operator (>=) to determine isEligible and
print its value.
●​ P: What will be the value of result in int result = 20 / 3;? Why?

Important Interview Questions

●​ Q: What is the difference between == and = in Java?


○​ A:
■​ == is the comparison (relational) operator. It is used to check if two values
are equal. It returns true or false.
■​ = is the assignment operator. It is used to assign a value to a variable.
●​ Q: Explain the difference between x++ (post-increment) and ++x (pre-increment).
○​ A:
■​ x++ (post-increment): The value of x is used first in the expression, and then
x is incremented by 1.
■​ ++x (pre-increment): The value of x is incremented by 1 first, and then the
new value is used in the expression.
●​ Q: What is the purpose of the modulus (%) operator?
○​ A: The modulus operator returns the remainder of a division operation. For
example, 10 % 3 returns 1.

7. Input/Output in Java
Introduction

Programming mein, sirf screen par kuch print karna hi kaafi nahi hota. Humein user se input bhi
lena padta hai, jaise user ka naam, age, ya koi number. Aur jo hum calculation karte hain, uska
output bhi dikhana hota hai.

Real-world Comparison

Imagine karo ki aap ek ATM machine use kar rahe ho. Aap apna card insert karte ho (input),
PIN enter karte ho (input). ATM aapka balance dikhata hai (output), ya cash deta hai (output).
Waise hi, Java programs bhi users se input lete hain aur unhein output dete hain.

Output in Java

Output ke liye hum already [Link]() use kar chuke hain.


●​ [Link]("text");: Prints the text and then moves to the next line. (ln = line)
●​ [Link]("text");: Prints the text but does not move to the next line.
●​ [Link]("formatted string", arguments);: Prints formatted output (similar to C's
printf).

Input in Java (Using Scanner class)

User se input lene ke liye, Java mein hum Scanner class ka use karte hain. Yeh class [Link]
package mein available hai.

Steps to take input:

1.​ Import the Scanner class: Aapko program ki shuruat mein import [Link];
likhna padega. Yeh Java ko batata hai ki hum Scanner class ko use karna chahte hain.
2.​ Create a Scanner object: Scanner input = new Scanner([Link]);
○​ Scanner: Class ka naam.
○​ input: Humne Scanner object ka naam input rakha hai. Aap kuch bhi rakh sakte ho.
○​ new Scanner([Link]): Yeh Scanner class ka ek naya object banata hai, aur
[Link] ka matlab hai ki input standard input source (keyboard) se aayega.
3.​ Use Scanner methods to read different types of input:
○​ [Link](): Integer input padhne ke liye.
○​ [Link](): Long integer input padhne ke liye.
○​ [Link](): Float input padhne ke liye.
○​ [Link](): Double input padhne ke liye.
○​ [Link](): Single word (token) as String padhne ke liye. (Space ke baad ka ignore
kar dega)
○​ [Link](): Poori line (including spaces) as String padhne ke liye.
4.​ Close the Scanner object: [Link](); Yeh good practice hai taki resources release ho
jaayein.

Sample Java Program with Output

import [Link]; // Step 1: Import the Scanner class​



public class InputOutputExample {​
public static void main(String[] args) {​
// Step 2: Create a Scanner object​
Scanner scanner = new Scanner([Link]);​

[Link]("Enter your name: ");​
String name = [Link](); // Step 3: Read String input
(full line)​

[Link]("Enter your age: ");​
int age = [Link](); // Step 3: Read integer input​

[Link]("Enter your height in meters (e.g., 1.75):
");​
double height = [Link](); // Step 3: Read double
input​

[Link]("\n--- Your Details ---"); // \n is for new
line​
[Link]("Name: " + name);​
[Link]("Age: " + age + " years old");​
[Link]("Height: %.2f meters\n", height); // Using
printf for formatted output​

[Link](); // Step 4: Close the scanner​
}​
}​

Sample Run and Output:

Enter your name: Priyanka​


Enter your age: 21​
Enter your height in meters (e.g., 1.75): 1.68​

--- Your Details ---​
Name: Priyanka​
Age: 21 years old​
Height: 1.68 meters​

Explanation of printf formatting:

●​ %.2f: Iska matlab hai ki ek floating-point number (f) print karo aur usmein decimal ke baad
only two digits (.2) tak rakho.
Important Note about nextLine() after nextInt()/nextDouble():

Jab aap nextInt() ya nextDouble() ke baad nextLine() use karte ho, toh ek choti si problem aa
sakti hai. nextInt() sirf number padhta hai aur keyboard buffer mein "Enter" key (\n) ko chhod
deta hai. Jab nextLine() call hota hai, toh woh usi \n ko read kar leta hai aur empty string return
karta hai.
Solution: nextLine() se pehle ek extra [Link]() call kar do, jo leftover \n ko consume
kar lega.
Example:
[Link]("Enter your age: ");​
int age = [Link]();​
[Link](); // Consume the leftover newline character​

[Link]("Enter your city: ");​
String city = [Link](); // Now this will work correctly​

Mini Practice Problems

●​ P: Write a Java program that asks the user for two numbers (integers) and then prints
their sum.
●​ P: Ask the user for their favorite color (a single word) and then print "Your favorite color is
[color]".
●​ P: Ask the user to enter their full name (with spaces) and print a greeting message. Make
sure to handle the nextLine() issue if you combine it with nextInt().

Important Interview Questions

●​ Q: How do you take input from the user in Java?


○​ A: We use the Scanner class from the [Link] package. We create a Scanner
object, typically new Scanner([Link]), and then use its methods like nextInt(),
nextLine(), nextDouble(), etc., to read different types of input.
●​ Q: What is the difference between [Link]() and [Link]()?
○​ A: [Link]() prints the output to the console and keeps the cursor on the
same line. [Link]() prints the output and then moves the cursor to the
next line.
●​ Q: Explain the common issue when using nextLine() after nextInt() or nextDouble(). How
can it be resolved?
○​ A: The nextInt() or nextDouble() methods only read the numerical input, leaving the
newline character (\n) in the input buffer. When nextLine() is called immediately
after, it consumes this leftover \n, resulting in an empty string. This can be resolved
by adding an extra [Link]() call to consume the newline character before
the actual nextLine() call is made.
I hope yeh pehle kuch topics aapko ache se samajh aaye honge. Humne fundamentals cover
kiye hain: Java kya hai, kaise install karte hain, pehla program kaise banate hain, aur variables
& operators kaise use karte hain. Agle section mein hum flow control statements (conditions
and loops) par jaayenge.
Koi bhi doubt ho, toh bejhijhak puchna! Keep practicing!

You might also like