CORE JAVA :-
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
CORE JAVA • 1-D ARRAY
• MULTI-DIMENSIONAL ARRAY
14. MATH CLASS
Uday Sharma 15. JAVA STRING CLASS
[email protected]1
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
• Basic Structure of a Java Program:-
• Java is one of the most popular programming languages because it is used in various tech
fields like app development, web development, client-server applications, etc.
• Java is an object-oriented programming language developed by Sun Microsystems of the
USA in 1991.
• It was originally called Oak by James Goslin. He was one of the inventors of Java.
• Java = Purely Object-Oriented.
How Java Works?
The source code in Java is first compiled into the bytecode.
Then the Java Virtual Machine(JVM) compiles the bytecode to the machine code.
• 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:-
public static void main(String[] args) {
//This is a single line comment
System.out.println("Hello World!!!");
2).Multi-Line Comments:-To write a multi-line comment just add a ‘/*…….*/’ at the start of the line.
Example:
public static void main(String[] args) {
/*This
* is
*a
* Multiline
* Comment
*/
System.out.println("Hello World!!!");
• 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
• Non-Primitive Data Types:-
These are of variable size & are usually declared with a ‘new’ keyword.
Eg : String, Arrays
String name = new String("uday sharma");
int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
6
• How to choose data types for our variables: -
In order to choose the data type, we first need to find the type of data we want to store. After that,
we need to analyze the min & max value we might use.
Output:-
• Literals :-
A constant value that can be assigned to the variable is called a literal.
• 101 – Integer literal
• 10.1f – float literal
7
• 10.1 – double literal (default type for decimals)
• ‘A’ – character literal
• true – Boolean literal
• “Harry” – String literal
• Keywords :-
Words that are reserved and used by the Java compiler. They cannot be used as an Identifier. Java
keywords are also known as reserved words. Keywords are particular words that act as a key to a
code. These are predefined words by Java so they cannot be used as a variable or object name or
class name.
Ex:-Abstract ,Boolean ,void ,public ,break ,byte ,case ,char ,class ,continue ,default , interface ,throw,
throws,final ,finally ,finalise ,do ,for ,while ,float ,int, String ,if , else ,else if , long, new ,null ,protected
,private ,short ,static , super ,this ,try ,catch etc…
Taking Input:-
We take input using the Scanner class and input various types of data using it.
To import the Scanner class - import java.util.Scanner;
Example :
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
float a = sc.nextFloat();
String name = sc.next();
String line = sc.nextLine();
Code:-
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
Checks if the left-hand side value is greater than the right-
> (Greater than) x > y --> True
hand side value. Returns a boolean value.
Checks if the left-hand side value is smaller than the right-
< (Less than) x < y --> False
hand side value. Returns a boolean value.
>=(Greater than or Checks if the left-hand side value is greater than or equal to
x >= y --> True
equal to) the right-hand side value. Returns a boolean value.
<= (Less than or equal Checks if the left-hand side value is less than or equal to
x <= y -->False
to) the right-hand side value. Returns a boolean value.
3. Logical Operators :-
• Let x = 8 and y =2
&& (logical
Returns true if both operands are true. x<y && x!=y --> True
and)
|| (logical
Returns true if any of the operand is true. x<y && x==y --> True
or)
! (logical Returns true if the result of the expression
!(x<y && x==y) --> False
not) is false and vice-versa
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.
Operator Description Example
& (bitwise
1&1 =1, 0&1=0,1&0=0,1&1=1, 0&0 =0 (A & B) = (100 & 011) = 000
and)
| (bitwise or) 1&0 =1, 0&1=1,1&1=1, 0&0=0 (A | B) = (100 | 011 ) = 111
^ (bitwise XOR) 1&0 =1, 0&1=1,1&1=0, 0&0=0 (A ^ B) = (100 ^ 011 ) = 111
This operator moves the value left by the number of bits
<< (left shift) 13<<2 = 52(decimal)
specified.
This operator moves the value left by the number of bits
>> (right shift) 13>>2 = 3(decimal)
specified.
• Conditional Statements ‘if-else’:-
• The if block is used to specify the code to be executed if the condition specified in if is true,
the else block is executed otherwise.
• The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
#if Statement:-
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
10
if(condition){
//code to be executed
}
If condition if-else condition
# if-else Statement:- The Java if-else statement also tests the condition. It executes the if
block if condition is true otherwise else block is executed.
Syntax:-
if (condition-to-be-checked) {
//statements-if-condition-true;
}
else {
//statements-if-condition-false;
}
# if-else ladder syntax:-
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:-
if (condition1) {
//Statements;
}
else if (condition2){
//Statements;
}
else {
//statements
}
11
Code:- this code will demonstrate both if-else and if-else ladder the statements:-
Output:-
12
#Java Nested if statement:-
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Output:-
• Conditional Statements ‘switch’:-
13
• 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:-
Nested for loop:-
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
17
Some other example of Nested loops:-
• We can use for loop for accessing the array like:-
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
=>While loop:- =>Do-while loop:-
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
• Break & Continue:-
Jumps in loops are used to control the flow of loops. There are two statements used to
implement jump in loops - Continue and Break. These statements are used when we need to
change the flow of the loop when some specified condition is met.
Continue statement is used to skip to the next iteration of that loop. This means that it stops one
iteration of the loop. All the statements present after the continue statement in that loop are not
executed.
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.
• Exception Handling (try-catch):-
Exception Handling in Java is a mechanism to handle the runtime errors so that normal flow of the
application can be maintained.
It is done using 2 keywords - ‘try’ and ‘catch’.
20
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
,float , Booleans etc.
• Advantages:-
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
• Disadvantages:-
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
1. Single Dimensional Array.
2. Multidimensional Array.
• Single Dimensional Array:- Below code showing arrays.
21
Output:-
22
Ex:-
Output:-
• Multidimensional Array:-
Syntax to Declare Multidimensional Array in Java:-
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
int[][] arr=new int[3][3];//3 row and 3 column .
code:-
23
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
• Java Math Methods:-
The java.lang.Math class contains various methods for performing basic numeric operations such
as the logarithm, cube root, and trigonometric functions etc. The various java math methods are as
follows:
Basic Math methods:-
Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to second argument.
Math.signum() It is used to find the sign of a given value.
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.nextUp() It returns the floating-point value adjacent to d in the direction of positive
infinity.
Math.nextDown() It returns the floating-point value adjacent to d in the direction of negative
infinity.
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.hypot() It returns sqrt(x2 +y2) without intermediate overflow or underflow.
Math.ulp() It returns the size of an ulp of the argument.
Math.getExponent() It is used to return the unbiased exponent used in the representation of a value.
Math.IEEEremainder() It is used to calculate the remainder operation on two arguments as prescribed
by the IEEE 754 standard and returns 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.decrementExact() It is used to return the argument decremented by one, throwing an exception if
the result overflows an int or long.
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
Returns a substring from start to the end.
5. substring(int start) Substring(3) returns “ substring”. [Note that
indexing starts from 0 (default)]
Returns a substring from the start index to the end
6. substring(int start, int end) index. The start index is included, and the end is
excluded.
Returns a new string after replacing C 1with C2.
7. replace(‘C1’, ‘C2’)
(This method takes char as argument)
Its check the string is starts with the given
8. startsWith(“ string ”)
statement or string .
Its check the string is ends with the given
9. endsWith(“string ”)
statement or string .
10. charAt(2) Returns the character at a given index position.
Returns the index of the first occurrence of the
11. indexOf(“s”)
specified character in the given string.
Returns the last index of the specified character
12. lastIndexOf(“”)
from the given string.
Returns true if the given string is equal to string
13. equals(string)
false otherwise [Case sensitive]
Returns true if two strings are equal, ignoring the [
14.equalsIgnoreCase(string)
lower and upper case] of characters.
Code:-
28
Output:-
29
➢ Go check out my LinkedIn profile for more notes and other resources content
@Uday Sharma
[email protected]
https://www.linkedin.com/in/uday-sharma-602b33267