0% found this document useful (0 votes)
9 views12 pages

Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems and currently owned by Oracle, widely used for various applications across multiple platforms. Key features of Java include its object-oriented nature, platform independence, ease of learning, security, and robustness. The document also explains the Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE), along with Java variables and data types.

Uploaded by

piyushnagar128
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)
9 views12 pages

Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems and currently owned by Oracle, widely used for various applications across multiple platforms. Key features of Java include its object-oriented nature, platform independence, ease of learning, security, and robustness. The document also explains the Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE), along with Java variables and data types.

Uploaded by

piyushnagar128
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
You are on page 1/ 12

Unit - I

What is Java?
Java is a popular high-level,object-oriented programming language that was originally developed by
Sun Microsystems and released in 1995. Currently, Java is owned by Oracle, and more than 3 billion
devices run Java. Java runs on a variety of pla orms, such as Windows, Mac OS, and the various
versions ofUNIX. Today Java is being used to develop numerous types of so ware applica ons,
including desktop apps, mobile apps, web apps, games, and much more.

Java programming language was originally developed by Sun Microsystems, which was ini ated by
James Gosling and released in 1995 as a core component of Sun Microsystems' Java pla orm (Java 1.0
[J2SE]).

Java Features
Java is a feature-rich language. Java is evolving con nuously with every update, and updates are
coming every six months. Following are some of the main features of the Java language:

Object Oriented: Java is a pure object-oriented language, and everything in Java is an object. Java
supports OOPS principles like Inheritance, Encapsula on, Polymorphism, Classes , and so on. Java itself
can be extended as well, being based on an object model.

Pla orm Independent: Java code is pla orm independent. A Java code is not compiled into machine-
specific code; it is compiled into a pla orm-neutral byte code. This byte code is executed by JVM which
runs the code on the underlying pla orm. This capability makes Java a Write Once Run Anywhere
language.

Easy To Learn: Java inherits features from C and C++, and developers can easily learn Java if they know
any of the C or C++ languages. Even for someone new to computer languages, Java is very easy to learn
from scratch.

Secure: Java is secure by architecture. A developer is not required to directly interact with the
underlying memory or opera ng system. Java provides automa c garbage collec on, so developers
are not required to worry about memory leaks, management, etc.

Architectural-Neutral: Java byte code can be executed on any kind of processor. JRE automa cally
handles the code execu on on different types of processors.

Portable: A Java code wri en on a Windows machine can be executed without any code change on
MacOS and vice versa. There is no need to make any opera ng system-specific code changes.

Robust: Java is a very robust language with very strong compile- me error checks, strict type checking,
and run me excep on handling.

Mul threading: Java provides inbuilt support for mul processing and mul threading. Java provides
thread handling, monitors, deadlock handling, racing condi ons, etc.

High Performance: Java, although being interpreted, is s ll very performant. The JIT(Just In Time)
compilerhelps in improving performance.

Distributed: Java is designed for distributed systems and is the most popular language for developing
internet-based applica ons as the internet is a distributed environment.

What is JVM (Java Virtual Machine)?


The JVM (Java Virtual Machine) is a virtual machine, an abstract computer that has its own ISA,
memory, stack, heap, etc. It runs on the host OS and places its demands for resources on it. The JVM

Page 1 of 12
Unit - I

(Java Virtual Machine) is a specifica on and can have different implementa ons, as long as they adhere
to the specs.

JVM (Java Virtual Machine) Architecture

What is JDK?
JDK is an abbrevia on for Java Development Kit which includes all the tools, executables, and binaries
required to compile, debug, and execute a Java Program.JDK is pla orm dependent i.e. there are
separate installers for Windows, Mac, and Unix systems. JDK includes both JVM and JRE and is en rely
responsible for code execu on.

What is JRE?
JRE is a Java Run me Environment which is the implementa on of JVM i.e. the specifica ons that are
defined in JVM are implemented and create a corresponding environment for the execu on of code.
JRE comprises mainly Java binaries and other classes to execute the program like JVM which physically
exists. Along with Java binaries JRE also consists of various technologies of deployment, user interfaces
to interact with code executed, some base libraries for different func onali es, and language

What is JVM?
JVM is the abbrevia on for Java Virtual Machine which is a specifica on that provides a run me
environment in which Java byte code can be executed i.e. it is something that is abstract and its
implementa on is independent of choosing the algorithm and has been provided by Sun and other
companies. It is JVM which is responsible for conver ng Byte code to machine-specific code. It can also
run those programs which are wri en in other languages and compiled to Java bytecode.

Difference between JDK, JRE, and JVM


Following are the important differences between JDK, JRE, and JVM −

Sr.
Key JDK JRE JVM
No.

JRE (Java Run me JVM (Java Virtual


JDK (Java
Environment) is the Machine) is an
Development Kit) is
implementa on of JVM and abstract machine that
a so ware
is defined as a so ware is pla orm-dependent
development kit to
package that provides Java and has three no ons
1 Defini on develop applica ons
class libraries, along with as a specifica on, a
in Java. In addi on to
Java Virtual Machine (JVM), document that
JRE, JDK also
and other components to describes requirement
contains number of
run applica ons wri en in of JVM
development tools
Java programming. implementa on,

Page 2 of 12
Unit - I

Sr.
Key JDK JRE JVM
No.

(compilers, JavaDoc, implementa on, a


Java Debugger etc.). computer program
that meets JVM
requirements, and
instance, an
implementa on that
executes Java byte
code provides a
run me environment
for execu ng Java byte
code.

JVM on other hand


JDK is primarily used specifies all the
On other hand JRE is
for code execu on implementa ons and
Prime majorly responsible for
2 and has prime responsible to provide
func onality crea ng environment for
func onality of these
code execu on.
development. implementa ons to
JRE.

JDK is pla orm


dependent i.e for
Pla orm Like of JDK JRE is also JVM is pla orm
3 different pla orms
Independence pla orm dependent. independent.
different JDK
required.

As JDK is responsible On other hand JRE does not


for prime contain tools such as
development so it compiler or debugger etc.
JVM does not include
contains tools for Rather it contains class
4 Tools so ware development
developing, libraries and other
tools.
debugging and suppor ng files that JVM
monitoring java requires to run the
applica on. program.

JVM = Only Run me


JDK = Java Run me JRE = Java Virtual Machine
environment for
5 Implementa on Environment (JRE) + (JVM) + Libraries to run the
execu ng the Java
Development tools applica on
byte code.

Java program to print "Hello World"


/* Online Java Compiler and Editor */
public class HelloWorld{

public sta c void main(String []args){


System.out.println("Hello, World!");
}

Page 3 of 12
Unit - I

1. Public Main Class


public class MyFirstJavaProgram {
This line is crea ng a new class MyFirstJavaProgram and being public, this class is to be defined in the
same name file as MyFirstJavaProgram.java. This conven on helps Java compiler to iden fy the name
of public class to be created before reading the file content.

2. Comment Sec on
/* This is my first java program.
* This will print 'Hello World' as the output
*/
These lines being in /* */ block are not considered by Java compiler and are comments. A comment
helps to understand program in a be er way and makes code readable and understandable.

3. Public Sta c Void Main


public sta c void main(String []args) {
This line represents the main method that JVM calls when this program is loaded into memory. This
method is used to execute the program. Once this method is finished, program is finished in single
threaded environment.

4. Keywords Used
Let's check the purpose of each keyword in this line.
 public − defines the scope of the main method. Being public, this method can be called by
external program like JVM.
 sta c − defines the state of the main method. Being sta c, this method can be called by
external program like JVM without first crea ng the object of the class.
 void − defines the return type of the main method. Being void, this method is not returning
any value.
 main − name of the method
 String []args − arguments passed on command line while execu ng the java command.

5. System.out.println() Method
System.out.println("Hello World"); // prints Hello World
System.out represents the primary console and its println() method is taking "Hello World" as input
and it prints the same to the console output.

Java Comments
Java comments are text notes wri en in the code to provide an explana on about the source code.
The comments can be used to explain the logic or for documenta on purposes.

Single Line Comment


The single-line comment is used to add a comment on only one line and can be wri en by using the
two forward slashes (//). These comments are the most used commen ng way.
Mul line Comment
The mul line (or, mul ple-line) comments start with a forward slash followed by an asterisk (/*) and
end with an asterisk followed by a forward slash (*/) and they are used to add comment on mul ple
lines.

Documenta on Comment
The documenta on comments are used for wri ng the documenta on of the source code. The
documenta on comments start with a forward slash followed by the two asterisks (/**), end with an
asterisk followed by a backward slash (*/), and all lines between the start and end must start with an
asterisk (*).

Page 4 of 12
Unit - I

What is a Java Variable?


A variable provides us with named storage that our programs can manipulate. Each variable in Java
has a specific type, which determines the size and layout of the variable's memory; the range of values
that can be stored within that memory; and the set of opera ons that can be applied to the variable.

Java Variables Types


The following are the three types of Java variables:
 Local variables
 Instance variables
 Class/Sta c variables

Java Local Variables


 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables, so local variables should be declared and an ini al
value should be assigned before the first use.

Java Instance Variables


 Instance variables are declared in a class, but outside a method, constructor or any block.
 When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
 Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor
or block, or essen al parts of an object's state that must be present throughout the class.
 Instance variables can be declared in class level before or a er use.

Java Class/Sta c Variables


 Class variables also known as sta c variables are declared with the sta c keyword in a class,
but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many objects
are created from it.
 Sta c variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final, and sta c. Constant variables never change from
their ini al value.
 Sta c variables are stored in the sta c memory. It is rare to use sta c variables other than
declared final and used as either public or private constants.
 Sta c variables are created when the program starts and destroyed when the program stops.
 Visibility is similar to instance variables. However, most sta c variables are declared public
since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for Booleans,
it is false; and for object references, it is null. Values can be assigned during the declara on or
within the constructor. Addi onally, values can be assigned in special sta c ini alizer blocks.
 Sta c variables can be accessed by calling with the class name ClassName.VariableName.

Java - Data Types


The Java data types are categorized into two main categories −
 Primi ve Data Types
 Reference/Object Data Types

Page 5 of 12
Unit - I

Java Primi ve Data Types


Primi ve data types are predefined by the language and named by a keyword. There are eight primi ve
data types supported by Java. Below is the list of the primi ve data types:

byte Data Type


The byte data type is an 8-bit signed two's complement integer with a minimum value of -128 (-2 7)
and a maximum value of 127 (inclusive) (27 -1).

short Data Type


The short data type is a 16-bit signed two's complement integer, which provides a range of values from
-32,768 (-215) to 32,767 (inclusive) (215 -1). Like the byte data type, the short data type is also beneficial
for saving memory, as it occupies less space compared to an integer, being only half the size.
The default value for a short variable is 0.

int Data Type


The int data type is a 32-bit signed two's complement integer, allowing for a wide range of values from
-2,147,483,648 (-231) to 2,147,483,647 (inclusive) (231 -1). Here the integer is generally used as the
default data type for integral values unless there is a concern about memory.
The default value for an int variable is 0.

long Data Type


The long data type is a 64-bit signed two's complement integer, capable of represen ng a vast range
of values from -9,223,372,036,854,775,808 (-263) to 9,223,372,036,854,775,807 (inclusive) (263 -1).
This data type is used when a wider range than int is needed, where its default value is 0L.

float Data Type


The float data type is a single-precision 32-bit IEEE 754 floa ng-point representa on. It is par cularly
useful for saving memory in large arrays of floa ng-point numbers. Its default value is 0.0f. However,
it's important to note that the float data type is not suitable for precise values, such as currency, due
to poten al rounding errors in floa ng-point arithme c.

double Data Type


The double data type is a double-precision 64-bit IEEE 754 floa ng-point representa on, which is
generally used as the default data type for decimal values, generally the default choice. Double data
type should never be used for precise values such as currency, where its default value is 0.0d.

boolean Data Type


The boolean data type represents a single bit of informa on and can hold one of two possible values:
true or false. This data type is used for simple flags that track true/false condi ons where its default
value is false.

Example
boolean one = true;

char Data Type


The char data type is a single 16-bit Unicode character, which represents a wide range of characters
from different languages and symbols. With a range '\u0000' (or 0) to '\uffff' (or 65,535 inclusive). This
data type is primarily used to store individual characters.

Example of Primi ve Data Types

public class JavaTester {


public sta c void main(String args[]) {

Page 6 of 12
Unit - I

byte byteValue1 = 2;
byte byteValue2 = 4;
byte byteResult = (byte)(byteValue1 + byteValue2);

System.out.println("Byte: " + byteResult);

short shortValue1 = 2;
short shortValue2 = 4;
short shortResult = (short)(shortValue1 + shortValue2);

System.out.println("Short: " + shortResult);

int intValue1 = 2;
int intValue2 = 4;
int intResult = intValue1 + intValue2;

System.out.println("Int: " + intResult);

long longValue1 = 2L;


long longValue2 = 4L;
long longResult = longValue1 + longValue2;

System.out.println("Long: " + longResult);

float floatValue1 = 2.0f;


float floatValue2 = 4.0f;
float floatResult = floatValue1 + floatValue2;

System.out.println("Float: " + floatResult);

double doubleValue1 = 2.0;


double doubleValue2 = 4.0;
double doubleResult = doubleValue1 + doubleValue2;

System.out.println("Double: " + doubleResult);

boolean booleanValue = true;

System.out.println("Boolean: " + booleanValue);

char charValue = 'A';

System.out.println("Char: " + charValue);


}
}

Output
Byte: 6
Short: 6
Int: 6
Long: 6
Float: 6.0
Double: 6.0

Page 7 of 12
Unit - I

Boolean: true
Char: A

Java Non-Primi ve (Reference/Object) Data Types


The non-primi ve data types are not predefined. The reference data types are created using
defined constructors of the classes. They are used to access objects. These variables are declared to
be of a specific type that cannot be changed. For example, Employee, Puppy, etc.
The following are the non-primi ve (reference/object) data types −
 String: The string is a class in Java, and it represents the sequences of characters.
 Arrays: Arrays are created with the help of primi ve data types and store mul ple values of
the same type.
 Classes: The classes are the user-defined data types and consist of variables and methods.
 Interfaces: The interfaces are abstract types that are used to specify a set of methods.

The default value of any reference variable is null. A reference variable can be used to refer to any
object of the declared type or any compa ble type.

The following example demonstrates the reference (or, object) data types.
Animal animal = new Animal("giraffe");

Java Type Cas ng


Type cas ng is a technique that is used either by the compiler or a programmer to convert one data
type to another in Java. Type cas ng is also known as type conversion. For example, conver ng int to
double, double to int, short to int, etc.
There are two types of type cas ng allowed in Java programming:
 Widening type cas ng
 Narrowing type cas ng

Widening Type Cas ng


Widening type cas ng is also known as implicit type cas ng in which a smaller type is converted into
a larger type, it is done by the compiler automa cally.
Hierarchy
Here is the hierarchy of widening type cas ng in Java:
byte>short>char>int>long>float>double

Narrowing Type Cas ng


Narrowing type cas ng is also known as explicit type cas ng or explicit type conversion which is done
by the programmer manually. In the narrowing type cas ng a larger type can be converted into a
smaller type.

Syntax
Below is the syntax for narrowing type cas ng i.e., to manually type conversion:
double doubleNum = (double) num;
The above code statement will convert the variable to double type.

User Input in Java


To take input from the user in Java, the Scanner class is used. The Scanner class a built-in class
of java.u l package. Java Scanner class provides many built-in methods to take different types of user
inputs from the users.

How to Use Scanner Class to Take User Input?


The following are the steps to use Scanner class for the user input in Java −

Step 1: Import Scanner Class

Page 8 of 12
Unit - I

Fist you need to import the Scanner class to use its methods. To import the Scanner class, use the
following import statement −
import java.u l.Scanner

Step 2: Create Scanner Class's Object


A er impor ng the Scanner class, you need to create its object to use its methods. To create an object
of the Scanner class, invoke Scanner() constructor.
Below is the statement to create an object of Scanner class −
Scanner obj = new Scanner(System.in);

Step 3: Take User Input


Scanner class provides a variety of methods which are useful to take user input of different types. For
example, if you want to input an integer value, use nextInt() method.
The following is the statement to take user input in Java −
int age = obj.nextInt();

The above statement will wait for an integer input from the user. When user provides an integer value,
that will be assign to "age" variable.

Integer Input from the User


The nextInt() method is used to take input of an integer from the user.

Float Input from the User


The nextFloat() method is used to take input of a float value from the user.

String Input from the User


The nextLine() method is used to take input of a string value from the user.

Java Operators
There are different types of operators in Java, we have listed them below −
 Arithme c Operators
 Assignment Operators
 Rela onal Operators
 Logical Operators
 Bitwise Operators
 Misc Operators

Java Arithme c Operators


Arithme c operators are used in mathema cal expressions in the same way that they are used in
algebra. The following table lists the arithme c operators −
Assume integer variable A holds 10 and variable B holds 20, then −
Operator Descrip on Example

+ (Addi on) Adds values on either side of the operator. A + B will give 30

Subtracts right-hand operand from le -hand


- (Subtrac on) A - B will give -10
operand.

Mul plies values on either side of the


* (Mul plica on) A * B will give 200
operator.

Divides le -hand operand by right-hand


/ (Division) B / A will give 2
operand.

Page 9 of 12
Unit - I

Divides le -hand operand by right-hand


% (Modulus) B % A will give 0
operand and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

Java Assignment Operators


Assignment Operators are used to assign values to variables. These operators modify the value of a
variable based on the opera on performed. The most commonly used assignment operator is =, but
Java provides mul ple compound assignment operators for shorthand opera ons.
Following are the assignment operators supported by Java language −
Operator Descrip on Example

Simple assignment operator. Assigns values from C = A + B will assign value of A +
=
right side operands to le side operand. B into C

Add AND assignment operator. It adds right


+= operand to the le operand and assign the result to C += A is equivalent to C = C + A
le operand.

Subtract AND assignment operator. It subtracts


-= right operand from the le operand and assign the C -= A is equivalent to C = C − A
result to le operand.

Mul ply AND assignment operator. It mul plies


*= right operand with the le operand and assign the C *= A is equivalent to C = C * A
result to le operand.

Divide AND assignment operator. It divides le


/= operand with the right operand and assign the C /= A is equivalent to C = C / A
result to le operand.

Modulus AND assignment operator. It takes


%= modulus using two operands and assign the result C %= A is equivalent to C = C % A
to le operand.

<<= Le shi AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shi AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Java Rela onal Operators


Rela onal operators are used to compare two values. These operators return a boolean result: true if
the condi on is met and false otherwise. Rela onal operators are commonly used in decision-making
statements like if condi ons and loops.
There are following rela onal operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −

Page 10 of 12
Unit - I

Operator Descrip on Example

Checks if the values of two operands are


== (equal to) equal or not, if yes then condi on (A == B) is not true.
becomes true.

Checks if the values of two operands are


!= (not equal to) equal or not, if values are not equal then (A != B) is true.
condi on becomes true.

Checks if the value of le operand is


> (greater than) greater than the value of right operand, (A > B) is not true.
if yes then condi on becomes true.

Checks if the value of le operand is less


< (less than) than the value of right operand, if yes (A < B) is true.
then condi on becomes true.

Checks if the value of le operand is


>= (greater than or greater than or equal to the value of
(A >= B) is not true.
equal to) right operand, if yes then condi on
becomes true.

Checks if the value of le operand is less


<= (less than or equal than or equal to the value of right
(A <= B) is true.
to) operand, if yes then condi on becomes
true.

Java Logical Operators


Logical operators are used to perform logical opera ons on boolean values. These operators are
commonly used in decision-making statements such as if condi ons and loops to control program flow.
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Operator Descrip on Example

Called Logical AND operator. If both the operands


&& (logical and) (A && B) is false
are non-zero, then the condi on becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condi on (A || B) is true
becomes true.

Called Logical NOT Operator. Use to reverses the


! (logical not) logical state of its operand. If a condi on is true !(A && B) is true
then Logical NOT operator will make false.

Java Bitwise Operators


Bitwise operators are used to perform opera ons at the binary (bit) level. These operators work on
individual bits of numbers. They are commonly used in low-level programming, encryp on, and
performance op miza on.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.

Page 11 of 12
Unit - I

Assume integer variable A holds 60 and variable B holds 13 then −


Operator Descrip on Example

Binary AND Operator copies a bit to


& (bitwise and) the result if it exists in both (A & B) will give 12 which is 0000 1100
operands.

Binary OR Operator copies a bit if it


| (bitwise or) (A | B) will give 61 which is 0011 1101
exists in either operand.

Binary XOR Operator copies the bit if


^ (bitwise XOR) (A ^ B) will give 49 which is 0011 0001
it is set in one operand but not both.

Binary Ones Complement Operator (⁓A ) will give -61 which is 1100 0011 in 2's
⁓ (bitwise
is unary and has the effect of complement form due to a signed binary
compliment)
'flipping' bits. number.

Binary Le Shi Operator. The le


operands value is moved le by the
<< (le shi ) A << 2 will give 240 which is 1111 0000
number of bits specified by the right
operand.

Binary Right Shi Operator. The le


operands value is moved right by the
>> (right shi ) A >> 2 will give 15 which is 1111
number of bits specified by the right
operand.

Shi right zero fill operator. The le


operands value is moved right by the
>>> (zero fill right shi ) number of bits specified by the right A >>>2 will give 15 which is 0000 1111
operand and shi ed values are filled
up with zeros.

Java Miscellaneous Operators


There are few other operators supported by Java Language.

Condi onal Operator ( ? : )


Condi onal operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should
be assigned to the variable. The operator is wri en as −
variable x = (expression) ? value if true : value if false

Instanceof Operator
This operator is used only for object reference variables. The operator checks whether the object is of
a par cular type (class type or interface type). instanceof operator is wri en as −
( Object reference variable ) instanceof (class/interface type)

Page 12 of 12

You might also like