Core Java Notes
Core Java Notes
1. OVERVIEW OF JAVA
2. JVM, JDK, JRE
3. COMMENTS
4. VARIABLES
5. DATA TYPES
6. LITERALS
7. KEYWORDS
8. SCANNER INPUT
9. OPEARTORS
10. CONTROL STATEMENTS.
• IF-ELSE
• SWITCH
11. LOOPS
• FOR LOOP
• WHILE LOOP
• DO-WHILE LOOP
12. BREAK, CONTINUE
13. ARRAY
JAVA:-
Java is an open-source, class-based, high-level, object-oriented programming language. Java is
platform independent as the java programs are compiled into byte code that are platform
independent.
• Features of Java:-
• Object Oriented: In Object Oriented programming everything is an object rather that
function and logic.
• Simple: Java is simple to understand, easy to learn and implement.
• Secured: It is possible to design secured software systems using Java.
• Platform Independent: Java is written once and run anywhere language, meaning
once the code is written, it can be executed on any software and hardware systems.
• Portable: Java is not necessarily fixated to a single hardware machine. Once created,
java code can be used on any platform.
• Architecture Neutral: Java is architecture neutral meaning the size of primitive type
is fixed and does not vary depending upon the type of architecture.
• Robust: Java emphasizes a lot on error handling, type checking, memory
management, etc. This makes it a robust language.
• Interpreted: Java converts high-level program statement into Assembly Level
Language, thus making it interpreted.
• Distributed: Java lets us create distributed applications that can run on multiple
computers simultaneously.
• Dynamic: Java is designed to adapt to ever evolving systems thus making it
dynamic.
• Multi-thread: multi-threading is an important feature provided by java for creating
web applications.
• High-performance: Java uses Just-In-Time compiler thus giving us a high
performance.
2
• JVM:-
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode
can be executed. It can also run those programs which are written in other languages and compiled
to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is
platform independent. There are three notions of the JVM: specification, implementation,
and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
• JRE:-
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a
set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
• JDK:-
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc),
etc. to complete the development of a Java Application.
3
• In this the file name is the same as the class name in the java:-
1. public static void main(String[]args){..} :-
• This is the main() method of our Java program.
• Every Java program must contain the main() method.
2. System.out.println("Hello World"):-
• The above code is used to display the output on the screen.
Anything passed inside the inverted commas is printed on the screen as plain text.
• Naming Conventions:-
• For classes, we use Pascal Convention. The first and Subsequent characters from a word are
capital letters (uppercase).
Example: Main, MyScanner, MyEmployee, codewithme
• For functions and variables, we use camelCaseConvention. Here the first character is
lowercase, and the subsequent characters are uppercase like myScanner, myMarks.
4
• Java Comments:-
Comments in any programming language are ignored by the compiler or the interpreter. A
comment is a part of the coding file that the programmer does not want to execute, rather the
programmer uses it to either explain a block of code or to avoid the execution of a specific part of
code while testing.
There are two types of comments:
1. Single-line comment
2. Multi-line comment
1). Single Line Comments:-
To write a single-line comment just add a ‘//’ at the start of the line.
Example:-
• Variables:-
1. A variable is a container that stores a value.
2. This value can be changed during the execution of the program.
3. Example: int number = 8; (Here, int is a data type, the number is the variable name, and 8 is
the value it contains/stores).
• Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable:-
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable:-
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
5
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable:-
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
Rules for declaring a variable name:-
We can choose a name while declaring a Java variable if the following rules are followed:
• Must not begin with a digit. (E.g., 1arry is an invalid variable)
• Name is case sensitive. (Harry and harry are different)
• Should not be a keyword (like Void).
• White space is not allowed. (int Code With Harry is invalid)
• Can contain alphabets, $character, _character, and digits if the other conditions are met.
• Data Types:-
Data types in Java fall under the following categories:-
1. Primitive Data Types (Intrinsic).
2. Non-Primitive Data Types (Derived).
• Primitive Data Types:-
Java is statically typed, i.e., variables must be declared before use. Java supports 8 primitive data
types:
boolean , byte ,char ,short ,int ,long ,float ,double data type
Output:-
• Literals :-
A constant value that can be assigned to the variable is called a literal.
• 101 – Integer literal
• 10.1f – float literal
7
Output:-
8
• Types of operators :-
1. Arithmetic Operators :-
Operator Description Example
+ (Addition) Used to add two numbers x+y=9
Used to subtract the right-hand side value from the left-hand side
- (Subtraction) x-y=5
value
*
Used to multiply two values. x * y = 14
(Multiplication)
/ (Division) Used to divide left-hand Value by right-hand value. x/y=3
Used to print the remainder after dividing the left-hand side value
% (Modulus) from x%y=1
the right-hand side value.
++ (Increment) Increases the value of operand by 1. x++ = 8
-- (Decrement) Decreases the value of operand by 1. y-- = 1
Code:-
Output:-
2. Comparison Operators :-
• Let x=7 and y=2.
Operator Description Example
x == y -->
== (Equal to) Checks if two operands are equal. Returns a boolean value.
False
Checks if two operands are not equal. Returns a boolean
!= (Not equal x != y --> True
value.
9
4. Bitwise Operators :-
• These operators perform the operations on every bit of a number.
• Let x =2 and y=3. So 2 in binary is 100, and 3 is 011.
if(condition){
//code to be executed
}
Code:- this code will demonstrate both if-else and if-else ladder the statements:-
Output:-
12
Output:-
• The Java switch statement executes one statement from multiple conditions. It is like if-else-
if ladder statement. The switch statement works with byte, short, int, long, enum types, String
and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the
switch statement.
• In other words, the switch statement tests the equality of a variable against multiple values.
• Switch case statements are a substitute for long if statements that compare a
variable to multiple values. After a match is found, it executes the
corresponding code of that value case.
Syntax:-
Switch(var) {
Case C1:
//Code;
break;
Case C2:
//Code;
break;
Case C3:
//Code
break;
default:
//Code }
14
Code:- Output:-
Note:-we can Nested Switch case like we use the nested if-else Statement:-
• Java Nested-switch Statement:-
We can use switch statement inside other switch statement in Java. It is known as nested switch statement.
15
Output:-
• Loops:-
A loop is used for executing a block of statements repeatedly until a particular condition is
satisfied. A loop consists of an initialization statement, a test condition and an increment
statement. There are three types of for loops in Java:-
16
1. For Loop:-
The syntax of the for loop is :-
for (initialization; condition; update) {
// body of-loop }
Code:- Output:-
2. While Loop :-
• The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean
condition is true. As soon as the Boolean condition becomes false, the loop automatically stops.
• The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it
is recommended to use the while loop.
The syntax for while loop is :
while(condition) {
// body of the loop }
18
3. Do-While Loop :-
• The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use a do-while loop.
• Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the
do-while check the condition at the end of loop body. The Java do-while loop is executed at least
once because condition is checked after loop body.
The syntax for the do-while loop is :
do {
// body of loop;
} while (condition);
19
int i;
for (i=7; i>0; i--) { // 0utput is :- 7 6 5 4 2 1
if (i==3) {
continue; // skip the part
}
System.out.println(i);
}
In this for loop, whenever i is a number divisible by 3, it will not be printed as the loop will skip to
the next iteration due to the continue statement. Hence, all the numbers except those which are
divisible by 3 will be printed.
• Break statement is used to terminate the current loop. As soon as the break statement is
encountered in a loop, all further iterations of the loop are stopped and control is shifted to the
first statement after the end of loop.
int i;
for (i=1; i<=20; i++) {
if (i == 11) {
break;
}
System.out.println(i); }
In this loop, when i becomes equal to 11, the for loop terminates due to break statement, Hence,
the program will print numbers from 1 to 10 only.
Additional keywords like finally, throw and throws can also be used if we dive deep into this
concept.
int[] marks = {98, 97, 95};
try {
System.out.println(marks[4]);
} catch (Exception exception) {
System.out.println("An exception for caught while accessing an index the 'marks' array");
}
System.out.println("We tried to print marks & an exception must have occurred with index
>=3");
• Arrays:-
Arrays in Java are like a list of elements of the same type i.e. a list of integers, character, string
Output:-
22
Ex:-
Output:-
• Multidimensional Array:-
Syntax to Declare Multidimensional Array in Java:-
Output:-
• Math class:-
Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
24
Math.pow() It returns the value of first argument raised to the power to second argument.
Math.ceil() It is used to find the smallest integer value that is greater than or equal to the
argument or mathematical integer.
Math.copySign() It is used to find the Absolute value of first argument along with sign specified in
second argument.
Math.nextAfter() It is used to return the floating-point number adjacent to the first argument in
the direction of the second argument.
Math.floor() It is used to find the largest integer value which is less than or equal to the
argument and is equal to the mathematical integer of a double value.
Math.floorDiv() It is used to find the largest integer value that is less than or equal to the
algebraic quotient.
Math.random() It returns a double value with a positive sign, greater than or equal to 0.0 and less
than 1.0.
Math.rint() It returns the double value that is closest to the given argument and equal to
mathematical integer.
25
Math.getExponent() It is used to return the unbiased exponent used in the representation of a value.
Math.addExact() It is used to return the sum of its arguments, throwing an exception if the result
overflows an int or long.
Math.subtractExact() It returns the difference of the arguments, throwing an exception if the result
overflows an int.
Math.multiplyExact() It is used to return the product of the arguments, throwing an exception if the
result overflows an int or long.
Math.incrementExact() It returns the argument incremented by one, throwing an exception if the result
overflows an int.
Math.negateExact() It is used to return the negation of the argument, throwing an exception if the
result overflows an int or long.
Math.toIntExact() It returns the value of the long argument, throwing an exception if the value
overflows an int.
Code:-some of the method is :-
26
Output:-
• String Class:-
Strings are immutable non-primitive data types in Java. Once a string is created it’s value cannot
be changed i.e. if we wish to alter its value then a new string with a new value has to be created.
This class in java has various important methods that can be used for Java objects. These include:
a. Concatenation(concat)
String name1 = new String("Aman");
String description = new String("is a good boy.");
String sentence = name1 + description;
System.out.println(sentence);
Sytem.out.println(name1.concat(description));
b. CharAt
String name = new String("Aman");
System.out.println(name.charAt(0))
c. Length
String name = new String("Aman");
System.out.println(name.length());
d. Replace
String name = new String("Aman");
System.out.println(name.replace('a', 'b'));
e. Substring
String name = new String("AmanAndAkku");
System.out.println(name.substring(0, 4));
• Java String class methods:-
The java.lang.String class provides many useful methods to perform operations on sequence of char
values.
Method Description
1. length() Returns the length of String .
Converts all the characters of the string to the lower
2. toLowerCase()
case letters.
Converts all the characters of the string to the
3. toUpperCase()
upper case letters.
Returns a new String after removing all the leading
4. trim()
and trailing spaces from the original string.
27
Output:-
29
➢ Go check out my LinkedIn profile for more notes and other resources content
@Uday Sharma
mrudaysharma4600@gmail.com
https://www.linkedin.com/in/uday-sharma-602b33267