-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavaBasics.txt
More file actions
233 lines (188 loc) · 7.16 KB
/
javaBasics.txt
File metadata and controls
233 lines (188 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
Java Basics
(Write Once, Run Anywhere)
Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
1. Sample Code
Let's look at the most basic Java program: Hello World.
Java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Understanding the Parts:
class Main: Everything in Java happens inside a class. We define a class named "Main". Ideally, the file name should also be Main.java.
public static void main(String[] args): This is the entry point.
public: Access modifier, means it can be accessed from anywhere.
static: It can be run without creating an object of the class.
void: It does not return any value.
main: The name of the method.
String[] args: Command line arguments. We can pass inputs to the program when running it from the command line.
System.out.println: The command to print output to the screen. println means "print line", so it moves to a new line after printing.
2. Comments
Comments are ignored by the computer. They are for humans to read.
Java
// This is a single line comment
/*
This is a
multi-line comment
*/
3. Data Types
Java has 8 primitive data types to store different values.
byte: 1 byte, small integers (-128 to 127)
short: 2 bytes, integers
int: 4 bytes, integers (Most common)
long: 8 bytes, large integers
float: 4 bytes, decimals (needs 'f' suffix, e.g., 3.14f)
double: 8 bytes, decimals (Most common for fractions)
char: 2 bytes, single character (e.g., 'A')
boolean: 1 bit, true or false
4. Operators
Arithmetic Operators
+ (Addition): Adds two values.
- (Subtraction): Subtracts the right operand from the left.
* (Multiplication): Multiplies two values.
/ (Division): Divides the left operand by the right.
% (Modulo): Returns the remainder of a division operation.
Unary Operators
Operators that require only one operand.
++ (Increment): Increases a value by 1.
-- (Decrement): Decreases a value by 1.
! (Logical NOT): Inverts the boolean value.
Relational Operators
Used to compare two values. They return a boolean result (true or false).
== (Equal to): Checks if two values are equal.
!= (Not equal to): Checks if two values are not equal.
> (Greater than): Checks if the left value is greater than the right.
< (Less than): Checks if the left value is less than the right.
>= (Greater than or equal to): Checks if the left value is greater than or equal to the right.
<= (Less than or equal to): Checks if the left value is less than or equal to the right.
Logical Operators
Used to determine the logic between variables or values.
&& (Logical AND): Returns true if both statements are true.
|| (Logical OR): Returns true if at least one of the statements is true.
Assignment Operators
Used to assign values to variables.
= (Assignment): Assigns the value on the right to the variable on the left.
+= (Add and Assign): Adds a value to the variable and assigns the result.
-= (Subtract and Assign): Subtracts a value from the variable and assigns the result.
*= (Multiply and Assign): Multiplies the variable by a value and assigns the result.
/= (Divide and Assign): Divides the variable by a value and assigns the result.
%= (Modulo and Assign): Assigns the remainder of the division to the variable.
5. Strings
Strings are objects in Java, not primitives. They store text.
Immutable: Once created, a String object cannot be changed. Modifying it creates a new object.
Java
String s1 = "Hello";
char[] arr = {'W', 'o', 'r', 'l', 'd'};
String s2 = new String(arr); // char array to string
System.out.println(s1 + " " + s2); // Concatenate: Hello World
System.out.println(s1.charAt(1)); // Char at index 1: 'e'
System.out.println(s1.length()); // Length: 5
System.out.println(s1.substring(0, 2)); // Substring: "He"
System.out.println(s1.equals("Hello")); // Check content equality: true
6. Input Output
For input, we use the Scanner class.
Java
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.next();
System.out.println(name + " is " + age);
}
}
What about BufferedReader?
BufferedReader is another way to read input. It is faster but harder to use (requires parsing strings to numbers manually). Scanner is easier and preferred for beginners.
7. Type Casting
Converting one data type to another.
Implicit (Widening): Small type to large type (e.g., int to double). This happens automatically by the compiler.
Explicit (Narrowing): Large type to small type (e.g., double to int). This must be done manually by the programmer.
Java
int myInt = 9;
double myDouble = myInt; // Automatic casting: 9.0
int heavyInt = (int) 9.78; // Manual casting: 9 (fraction lost)
8. Constants
Use the final keyword to create constants. These values cannot be changed.
Java
final float PI = 3.14f;
// PI = 3.15f; // This will cause an error
9. Arrays
Storing multiple values of the same type.
Java
int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[0]); // 90
// For-Each Loop
for (int i : scores) {
System.out.println(i);
}
// 2D Array
int[][] matrix = { {1, 2}, {3, 4} };
10. Conditional Statements
If, Else If, Else
Java
int marks = 85;
if (marks > 90) {
System.out.println("A");
} else if (marks > 80) {
System.out.println("B");
} else {
System.out.println("C");
}
Explanation: The program checks the condition marks > 90. Since 85 is not greater than 90, it moves to the next condition marks > 80. This is true, so it prints "B". The rest of the chain is skipped.
Switch
Java
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid");
}
Explanation: The computer checks the value of day. It matches with case 2 and executes the code inside it.
break: This keyword stops the code from running into the next case automatically (no "fall-through").
default: This runs if no case matches the value (like an else).
11. Loops
For Loop
Java
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
While Loop
Java
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do While Loop
Java
int i = 0;
do {
System.out.println(i); // Runs at least once
i++;
} while (i < 5);
12. Exception Handling
Handling errors so the program doesn’t crash.
Java
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // Error
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
Summary
We covered the fundamental building blocks of Java:
Structure: Class based, main method
Data: Types, Variables, Arrays, Strings
Logic: Operators, If-Else, Switch
Control: Loops (for, while)
Safety: Exception Handling
Practice writing these snippets to get comfortable with the syntax!