Java Notes
Java Notes
LANGUAGE
What is Java?
Java is a programming language and a platform. Java is a
high level, robust, object-oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary
of Oracle) in the year 1995. James Gosling is known as the father of
Java. Before Java, its name was Oak. Since Oak was already a
registered company, so James Gosling and his team changed the name
from Oak to Java.
Platform: Any hardware or software environment in which a program
runs, is known as a platform. Java has a runtime environment (JRE)
and API, it is called a platform.
Java Example
//File name save in the system
Simple.java
_________________________________________________
class Simple{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Application
According to Sun, 3 billion devices run Java. There are many
devices where Java is currently used. Some of them are as follows:
1.Desktop Applications such as acrobat reader, media player, antivirus,
etc.
2.Web Applications such as irctc.co.in, javatpoint.com, etc.
3.Enterprise Applications such as banking applications.
4.Mobile
5.Embedded System
6.Smart Card
7.Robotics
8.Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java
programming:
1) Standalone Application
Standalone applications are also known as desktop applications or
window-based applications. These are traditional software that we need to
install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is
called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications,
etc. is called an enterprise application. It has advantages like high-level
security, load balancing, and clustering.
4) Mobile Application
An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating
mobile applications.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such
as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes
core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and
enterprise applications. It is built on top of the Java SE platform. It includes
topics like Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Java User Input
The Scanner class is used to get user input, and it is found in
the java.util package.
To use the Scanner class, create an object of the class and use any of
the available methods found in the Scanner class documentation.
In our example, we will use the nextLine() method, which is used to read
Strings:
How JAVA differs from C And C++
Java and C
The major difference between Java and C is the Java is Object
Oriented language and has mechanism to define classes and object. The
Java team did not include some of the c features in Java:
1) Java does not include the C unique statement keywords sizeof and
typedef.
2) Java does not contain the data type struct and union.
3) Java does not support an explicit pointer type.
4) Java does not define the type modifiers keyword auto, extern, register,
signed, and unsigned.
5) Java does not preprocessor and therefore we cannot use # Include, #
define and ifdef statement
6) Java requires that the function with no arguments must be declared with
empty parenthesis and not with the void keyword as done in c.
7) Java adds new operators such as instanceof and >>>
8) Java adds labelled break and continue statements.
9) Java adds many features required for object-oriented programming.
JAVA And C++
1)Codes in C++ need to be compiled into every platform you use it on.
However, Java is portable, allowing it to be executed on all platforms.
2) C++ source code is compiled in the form of an object code that
produces an output when executed, while Java source code is a byte
code, which makes it platform-independent.
3) In C++, developers need to allocate and deallocate memory to the
code manually with operators like new and delete, but that is not the
case with Java as the system allocates the memory for the code on its
own.
4) Unlike C++, Java does not support multiple inheritance. However, Java can use interfaces to
gain the same result as in multiple inheritance.
5) C++ is an object-oriented and procedural programming language, which is why it does not
follow specific root hierarchies, while Java is completely an object-oriented language with one
root hierarchy.
Features C++ Java
Platform Independence Platform-dependent Platform-independent
Interpreter and Compiler Compiled programming Compiled and interpreted
language language
Thread Support Does not support thread Has built-in thread support
via the “thread” class
Token in Java
In Java, tokens are the basic building blocks of a program. They are the
smallest individual units of a program that have meaning to the compiler and
are used to represent the various elements of a program, such as keywords,
identifiers, operators, and literals.
Keywords:
These are reserved words that have a specific meaning in the Java language.
Examples of keywords in Java include class, public, private, if, else, while, for,
switch, case, break, continue, return, and static, among others.
In Java, a keyword is a reserved word that has a specific meaning and purpose
within the language. Keywords are used to define various constructs, such as
control flow statements, data types, access modifiers, and more.
As a token in Java, a keyword is a sequence of characters that are treated as a
single unit by the Java compiler. When Java code is compiled, the compiler
recognizes keywords as special words with a predefined meaning and function
within the language.
Examples of Java keywords include:
public, private, protected: access modifiers used to control access to
class members.
class, interface, enum: used to define different types of Java classes.
if, else, switch, while, do, for: used to define control flow statements.
int, float, boolean, char: used to define data types.
These are symbols or token bus that are used to perform operations on
operands, such as arithmetic operations (+, -, *, /, %), logical operations (&&,
||, !), relational operations (==, !=, <, >, <=, >=), and assignment operations (=,
+=, -=, *=, /=, %=, etc.).
In Java, an operator is a symbol that represents a specific action or computation
that can be performed on one or more operands. Operators are used to
manipulate and compare data values in Java programs.
Arithmetic Operators: Used to perform arithmetic operations such as
addition, subtraction, multiplication, division, and modulo. Examples: +, -, *, /,
%.
Relational Operators: Used to compare values and determine the relationship
between them. Examples: ==, !=, <, >, <=, >=.
Logical Operators: Used to perform logical operations on boolean values.
Examples: && (logical AND), || (logical OR), ! (logical NOT).
Bitwise Operators: Used to perform bitwise operations on binary values.
Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise
NOT), << (left shift), >> (right shift), >>> (unsigned right shift).
Assignment Operators: Used to assign values to variables. Examples: =, +=, -
=.
2. Relational Operators :
Symb Description Example-1 Example-2
ol
< Less than >>> 7<10 >>> ‘MTM_BIHTA’
True <’BCA’
False
> Greater Than >>> 7 >10 >>>’MTM_BIHTA’ >
False ‘BCA’
True
<= Less than or equal to >>> 7<=10 >>>’MTM_BIHTA’
True <=’BCA’
False
>= Greater than or equal to >>> 7>=10 >>>’MTM_BIHTA’>=’B
False CA’
True
!=, <> Not equal to >>> 7!=10 >>>’MTM_BIHTA’!=‘mt
True m_bihta’
True
1. Arithmetic Operators :
Symb Description Example-1 Example-2
ol
+ Addition >>>5+6 >>>’MTM’+’B
11 CA’
MTMBCA
- Subtraction >>>10-5 >>>5 – 6
5 -1
* Multiplication >>> 5*6 >>>’MTM’ * 2
30 MTMMTM
/ Division >>> 10 / 5 >>>5 /2.0
2 2.5
% Remainder / Modulo >>> 5 % 2 >>>15%5
1 0
** Exponentiation >>> 2**3 >>>2**8
8 256
// Integer Division >>> 7.0 // 2 >>>3//2
3.0 1
3. Logical Operators :
and If both the operands are true, then the >>>7<10 and 7 >20
condition False
becomes TRUE
+= added and assign back the result to left operand >>> x+=2 7
-= subtracted and assign back the result to left operand >>> x-=2 3
*= multiplied and assign back the result to left operand >>> x*=2 10
/= divided and assign back the result to left operand >>> x/=2 2
%= operands and assign the result to left operand taken >>> x%=2 1
modulus using two
//= performed floor division on operators and assign value >>> x//=2 2.5
Bitwise – Computer programming, which we all know as ‘Programs’, are assisted in
carrying out some arithmetic and logical operations. So, these programs work on the
level of one or more-bit patterns. The need for this is used to manipulate values for
comparisons and calculations.
Bitwise Operator: a bit is the smallest unit of data storage and it can have only one of
the two values, 0 and 1. Bitwise operators works on bits and perform bit-by-bit
operation.
Let us understand what are Decimal or base 10 numbers and Binary or Base
2 numbers, and then we will continue with the operator’s explanations.
Decimal or Base 10 – Decimals are the numbers that we give the program as an input
so as to perform an operation. These are understandable by a human. You may also
think of Decimals as the numbers that we use in day to day life (i.e. 0 to 9). It is also
known as base 10 because there are 10 numbers between 0 to 9.
5. Bitwise Operator:
<< Left shift operator: The left-hand side operand bit is moved 0010 << 2
left by the number specified on the right-hand side (Multiply
by 2) gives 8
>> Left shift operator: The left-hand side operand bit is moved 0100 << 2
left by the number
specified on the right-hand side (Divided by 2) gives 1
Types of bitwise operators –
Complements – Refer to the examples
1. And – 4 & 8
(4 = 0100 and 8 = 1000; so, AND value will be 0000, which is 0).
Hence the output.
2. OR – (0l0 = 0; 0I1 = 1; 1I0 = 1; 1I1 =1)
3. XOR – (0^0 = 0; 0^1 = 1; 1^0 = 1; 1^1 = 0)
4. Left Shift – Refer to the examples
5. Right Shift – Refer to the examples
1. Bitwise AND operators – if both the comparing bits are 1, then the Bitwise AND will
return 1 otherwise 0.
2. Bitwise OR Operators – if both the comparing bits are 1, it will return 1, or if both the bits
are 0, it will return 0 as a value.
3. Bitwise XOR Operators – the XOR operator will return 1 as a value if any of the bit is 0 or
1. But if both the bots are either 0 or 1, then it will return 0.
Binary or Base 2 – 0’s and 1’s make the binary numbers; these are
understandable by the computers. So all the binary numbers are made of just
these, i.e. 0’s and 1’s and thus called base 2 numbers.
Let us take X = 9 and Y = 65 and carry out the calculations. So the binary
values will be X = 0110 and Y = 1000.
4. Bitwise One’s Compliment Operators – The bitwise One’s operator for A
will be –(A+1).
5. Bitwise left shift Operators – In the bitwise left shift operator, the binary
number is appended with complying 0’s at the end.
6. Bitwise right shift Operators – In the bitwise right shift operators, the right
side’s bits are removed.
Separators:
These are symbols that are used to separate different parts of a program, such as
commas (,), semicolons (;), parentheses (()), braces ({ }), and brackets ([]).
In Java, separators are characters used to separate or group parts of a Java
program. Separators are not operators and do not perform any operations on
data values.
Java has several types of separators:
Semicolons (;): Used to separate statements in Java. Every statement in Java
must end with a semicolon.
Commas (,): Used to separate multiple arguments or parameters in method
calls or definitions or to separate multiple variable declarations.
Parentheses (( and )): Used to group expressions, define method parameters,
and control the order of evaluation.
Braces ({ and }): Used to define a block of code, such as a method body or a class definition.
Brackets ([ and ]): Used to define arrays or to access individual elements of an array.
Periods (.): Used to access class members or invoke methods on objects.
Colon (:): Used in switch statements and for-each loops to separate case values or to define
iteration variables.
Separators play an important role in structuring and organizing Java code, and using them
correctly is crucial for writing correct and readable programs.
Q. Have you ever read about the BODMAS rule in arithmetic?
Ans.:- It'll undoubtedly be YES!
B-Bracket
O-Order
D-Division
M-Multiplication
A-Addition
S-Subtraction
are all acronyms for BODMAS.
When various arithmetic operations are present in an equation, this rule specifies the
sequence they should be computed.
If we peek at the precedence chart given above, we'll notice that the order of operators
is in the following manner:
P-Parentheses
E- Exponentiation
M- Multiplication
D- Division
A- Addition
S- Subtraction
PEMDAS is the acronym for this rule, which
parallels BODMAS.
Literals:
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
Scanner input = new Scanner(System.in);
we have created an object of Scanner named input.
The System.in parameter is used to take input from the standard input.
It works just like taking inputs from the keyboard.
We have then used the nextLine() method of the Scanner class to read
a line of text from the user.
Import Scanner Class
we need to import the java.util.Scanner package before we can use
the Scanner class.
import java.util.Scanner;
Input Types
We used the nextLine() method, which is used to read Strings. To
read other types, look at the table below:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:"); // String input
String name = myObj.nextLine(); // Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble(); // Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
CONTROL STATEMENTS
If Statements
A one-way if statement executes the statements if the condition is true. The syntax for a
one-way if statement is:
if (boolean-expression)
statement(s) # Note that the statement(s) must be
indented
• The reserved word if begins a if statement.
• The condition is a Boolean expression that determines whether or not the body will be
executed.
• The block is a block of one or more statements to be executed if the condition is true.
The statements within the block must all be indented the same number of spaces from
the left. The block within an
If-else statements
If-else statements
A two-way if-else statement decides which statements to execute
based on whether
the condition is true or false.
The syntax for a two-way if-else statement:
if (boolean-expression)
statement(s) //for-the-true-case
else:
statement(s) //for-the-false-case
Ne s t e d i f s t a t e m en t s .
A series of tests can written using nested if
statements.
Example: Nestedif
float percent= 91
if (percent >= 90.00):
print ('congratuations, you got an A')
else:
if (percent >= 80.0):
print ('you got a B')
else:
if (percent >= 70.0):
print ('you got a C')
else:
print ('your grade is less than a C')
If_elif_else Statement
In Java we can define a series of conditionals (multiple
alternatives) using if for the first one, else if for the rest, up until the
final (optional) else for anything not caught by the other
conditionals.
Example:If_else if_else
score=int(input("Enter Score"))
if score >= 90.0:
grade = 'A'
else if score >= 80.0:
grade = 'B'
else if score >= 70.0:
grade = 'C'
else if score >= 60.0:
grade = 'D'
else:
grade = 'F'
print("Grade=",grade)
Using else if instead of else if will trigger a syntax error and
is not allowed.
Example:
class switchcasetest{ public static void main(String[] args)
{ int num=10;
switch(num)
{
case 1: System.out.println(“Monday”);
break;
case 2: System.out.println(“Tuesday”);
break;
case 3: System.out.println(“Wednesday”);
break;
case 4:
System.out.println(“Thursday”);
break;
case 5:
System.out.println(“Friday”);
break;
case 6:
System.out.println(“Saturday”);
break;
case 7:
System.out.println(“Sunday”);
break;
default:
System.out.println(“~~~ Invalid Week day No ~~~~”);
break;
}
}
}
II. Branchi
Examples:
public class WhileDemo {
public static void main(String args[])
{
int n = 10;
while(n > 0)
{
System.out.println("Count Doun Value" + n);
n - -;
}
}
}
For:- The for loop operates as follows.
The loop first starts, the initialization portion of the loop is
executed . It is an expression that sets the value of the loop control
variable, which acts as a counter that controls the loop.
It is important to understand that the initialization expression
is executed only once. Next, condition is evaluated.
This must be a Boolean expression. It usually tests the
loop control variable against a target value.
If this expression is true, then the body of the loop is
executed. If it is false, the loop terminates. Next, the iteration
portion of the loop is executed.
This is usually an expression that increments (++) or
decrements (- -) the loop control variable. The loop then iterates, first
evaluating the conditional expression, then executing the body of the
loop, and then executing the iteration expression with each pass. This
process repeats until the controlling expression is false.
Arrays
An array is a collection of similar data type, identified by a common
name and stored in consecutive memory location. Array elements can be
conveniently accessed using index number.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
Types of Array in java
There are two types of array.
1.Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array in Java