Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

L2 _Java Basics.pptx

The document provides an overview of Java, covering its characteristics as a general-purpose, object-oriented programming language, and details about the Java platform, including JDK, JRE, and JVM. It explains the types of variables in Java—local, instance, and static—and their respective scopes and characteristics. Additionally, it discusses operators in Java and their various types, including arithmetic and assignment operators.

Uploaded by

jay800440
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

L2 _Java Basics.pptx

The document provides an overview of Java, covering its characteristics as a general-purpose, object-oriented programming language, and details about the Java platform, including JDK, JRE, and JVM. It explains the types of variables in Java—local, instance, and static—and their respective scopes and characteristics. Additionally, it discusses operators in Java and their various types, including arithmetic and assignment operators.

Uploaded by

jay800440
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Variables in Java

(beginnersbook.com)

1
DR. APJ ABDUL KALAM TECHNICAL UNIVERSITY

Branch - IT
Web Technology (KIT - 501)

L1
Java Basics
By

Dr. Ruchi Gupta


Department of Information Technology
Ajay Kumar Garg Engineering College, Ghaziabad
2
JAVA
• Java is a general-purpose, class-based, object-oriented
programming language designed for having lesser
implementation dependencies.
• It is a computing platform for application development.
• Java is fast, secure, and reliable, therefore. It is widely used for
developing Java applications in laptops, data centers, game
consoles, scientific supercomputers, cell phones, etc.

3
Java Platform

• Java Platform is a collection of programs that help


programmers to develop and run Java programming
applications efficiently.
• It includes an execution engine, a compiler, and a set of libraries
in it. It is a set of computer software and specifications.
• James Gosling developed the Java platform at Sun
Microsystems, and the Oracle Corporation later acquired it.

4
Java Platform
1. JDK (Java Development Kit) is a Kit that provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) that includes two things
Development Tools(to provide an environment to develop your java programs)JRE (to
execute your java program).
2. JRE (Java Runtime Environment) is an installation package that provides an
environment to only run(not develop) the java program(or application)onto your
machine. JRE is only used by those who only want to run Java programs that are
end-users of your system.
3. JVM (Java Virtual Machine)is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into
JVM and JVM is responsible for executing the java program line by line, hence it is also
known as an interpreter.

5
6
Step-by-Step Execution of Java Program

• Whenever a program is written in JAVA, the javac compiles it.


• The result of the JAVA compiler is the .class file or the
bytecode and not the machine’s native code (unlike the C
compiler).
• The bytecode generated is a non-executable code and needs
an interpreter to execute on a machine. This interpreter is the
JVM and thus the Bytecode is executed by the JVM.
• And finally, the program runs to give the desired output.

7
Step-by-Step Execution of Java
Program

8
9
Steps to Implement Java Program

Implementation of a Java application program


involves the following step. They include:
1.Creating the program
2.Compiling the program
3.Running the program

10
class Test
{
public static void main(String []args)
{
System.out.println("My First Java Program.");
}
};

11
File Save: d:\Test.java

2. Compiling the Program in Java


• To compile the program, we must run the Java compiler (javac), with the name of the source file on the
“command prompt” like as follows
• If everything is OK, the “javac” compiler creates a file called “Test.class” containing the byte code of the
program.

3. Running the Program in Java


• We need to use the Java Interpreter to run a program. Java is easy to learn, and its syntax is simple and easy
to understand. It is based on C++ (so easier for programmers who know C++).
• The process of Java programming can be simplified in three steps:
• Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
• Compile it by typing “javac HelloWorld.java” in the terminal window.
• Execute (or run) it by typing “java HelloWorld” in the terminal window.

12
Main Features of JAVA

Platform independent language


Compiler(javac) converts source code (.java file) to the byte
code(.class file).
JVM executes the bytecode produced by compiler. This byte code can
run on any platform such as Windows, Linux, Mac OS etc. Which
means a program that is compiled on windows can run on Linux and
vice-versa.
Each operating system has different JVM, however the output they
produce after execution of bytecode is same across all operating
systems. That is why we call java as platform independent language.

13
Object Oriented language

4 main concepts of Object Oriented programming are:


•Abstraction
•Encapsulation
•Inheritance
•Polymorphism

14
Simple

• Java is considered as one of simple language because it does not have


complex features like:
Operator overloading
Multiple inheritance
Pointers
Explicit memory allocation

15
Robust Language

• Robust means reliable. Java programming language is developed in a


way that puts a lot of emphasis on early checking for possible errors,
that’s why java compiler is able to detect
• The main features of java that makes it robust are:
• Garbage Collection
• Exception Handling
•Memory Allocation.

16
• Secure
• Java programs run inside a virtual machine which is known as a sandbox.
• Java does not support explicit pointer.
• Byte-code verifier checks the code fragments for illegal code that can violate access right to
object.
• It provides java.security package implements explicit security.
• It provides library level safety.
• Run-time security check takes place when we load new code.

• Java is distributed: The java programs can be distributed on more than one systems that are
connected to each other using internet connection. Objects on one JVM (java virtual machine)
can execute procedures on a remote JVM.

17
Multithreading :Java supports multithreading. Multithreading is a
Java feature that allows concurrent execution of two or more parts of a
program for maximum utilisation of CPU.
Portable
• As discussed above, java code that is written on one machine can run
on another machine. The platform independent byte code can be
carried to any platform for execution that makes java code portable.

18
19
• The javac compiler does this thing, it takes java program (.java file
containing source code) and translates it into machine code (referred as byte code
or .class file).
• Java Virtual Machine (JVM) is a virtual machine that resides in the real machine
(your computer) and the machine language for JVM is byte
code.
• JVM executes the byte code generated by compiler and produce output. JVM
is the one that makes java platform independent.
• Each operating system has different JVM, however the output they
produce after execution of byte code is same across all operating
systems. Which means that the byte code generated on Windows can be run on
Mac OS and vice versa. That is why we call java as platform independent language.

20
JVM Architecture

21
• :Class Loader The class loader reads the .class file and save the byte code in the method area.
• Method Area: There is only one method area in a JVM which is shared among all the classes. This
holds the class level information of each .class file.
• Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for
each .class file.
• Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary
variables.
• PC Registers: This keeps the track of which instruction has been executed and which one is going to
be executed. Since instructions are executed by threads, each thread has a separate PC register.
• Native Method stack: A native method can access the runtime data areas of the virtual machine.
• Native Method interface: It enables java code to call or be called by native applications. Native
applications are programs that are specific to the hardware and OS of a system.
• Garbage collection: A class instance is explicitly created by the java code and after use it is
automatically destroyed by garbage collection for memory management.

22
Java v/s Python
TOPIC Java Python

Java is both compiled and interpreted language,


Compilation process which is first compiled and then interpreted into a Python is an interpreted programming language
byte code.

3-5 times shorter than equivalent Java


Code Length Longer lines of code as compared to python.
programs.

Define particular block by curly braces, end No need of semi colons and curly braces, uses
Syntax Complexity
statements by ; indentation

Strongly typed, need to define the exact datatype Dynamic, no need to define the exact datatype
Ease of typing
of variables of variables.

Java is much faster than python in terms of


Speed of execution Expected to run slower than Java programs
speed.

Multiple inheritance is partially done through


Multiple Inheritance Provide both single and multiple inheritance
interfaces
23
Ajay Kumar Garg Engineering College, Ghaziabad
(College Code: 027)

Web Technologies
L2
Java Basics

9/12/2023
Variables in Java

• A variable is a container which holds the value while


the Java program is executed.
• A variable is assigned with a data type.
• Variable is a name of memory location.
• There are three types of variables in java: local, instance
and static.
• There are two types of data types in Java: primitive and
non-primitive.

25
Types of Variables in Java

There are 3 types of variables in Java.


1. Local variable

2. Instance variable

3. Static variable

26
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.
• 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.

27
1) Local Variable

A variable defined within a block or method or constructor is called a local variable.


•These variables are created when the block is entered, or the function is called and
destroyed after exiting from the block or when the call returns from the function.
•The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
•Initialization of the local variable is mandatory before using it in the defined scope.
Time Complexity of the Method:
Time Complexity: O(1)
Auxiliary Space: O(1)

28
// Java Program to implement
// Local Variables
import java.io.*;

class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


System.out.println("Local Variable: " + var);
}
}

OutputLocal Variable: 10
29
2) Instance variable

Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.
•As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
•Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.
•Initialization of an instance variable is not mandatory. Its default value is dependent
on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for
Wrapper classes like Integer it is null, etc.
•Instance variables can be accessed only by creating objects.
•We initialize instance variables using constructors while creating an object. We can
also use instance blocks to initialize the instance variables.
The complexity of the method:
Time Complexity: O(1)
Auxiliary Space: O(1)
30
// Java Program to demonstrate
// Instance Variables
import java.io.*;

class GFG {

// Declared Instance Variable


public String geek;
public int i;
public Integer I;
public GFG()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Shubham Jain";
}

// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();

// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is "
+ name.i);

// toString() called internally


System.out.println("Default value for Integer is "
+ name.I);
}
}

OutputGeek name is: Shubham Jain Default value for int is 0 Default value for Integer is null 31
3) Static variable
Static variables are also known as class variables.
•These variables are declared similarly to instance variables. The difference is that static variables are declared
using the static keyword within a class outside of any method, constructor, or block.
•Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many
objects we create.
•Static variables are created at the start of program execution and destroyed automatically when execution
ends.
•Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable.
For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
•If we access a static variable like an instance variable (through an object), the compiler will show a warning
message, which won’t halt the program. The compiler will replace the object name with the class name
automatically.
•If we access a static variable without the class name, the compiler will automatically append the class name.
But for accessing the static variable of a different class, we must mention the class name as 2 different classes
might have a static variable with the same name.
•Static variables cannot be declared locally inside an instance method.
•Static blocks can be used to initialize static variables.
The complexity of the method:
Time Complexity: O(1)
Auxiliary Space: O(1)
32
// Java Program to demonstrate
// Static variables
import java.io.*;

class GFG {
// Declared static variable
public static String geek = "Shubham Jain";

public static void main(String[] args)


{

// geek variable can be accessed without object


// creation Displaying O/P GFG.geek --> using the
// static variable
System.out.println("Geek Name is : " + GFG.geek);

// static int c=0;


// above line,when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}

OutputGeek Name is : Shubham Jain 33


Operator in Java
• Operators are used to perform operations on variables
and values.
• Operator in Java is a symbol that is used to perform
operations. For example: +, -, *, / etc.
• There are many types of operators in Java which are given
below:

34
Types of Operator in Java
• Arithmetic Operators
• Assignment Operators
• Logical Operators
• Relational Operators
• Unary Operators
• Bitwise Operators
• Ternary Operators
• Shift Operators

35
Arithmetic Operators in Java

• Arithmetic Operators are used to perform mathematical


operations like addition, subtraction, etc. Assume that A = 10
and B = 20 for the below table.
public class
ArithmeticOperators {
public static void
main(String[] args) {
int A = 10;
int B = 20;
System.out.println(A + B);
System.out.println(A - B);
System.out.println(A * B);
System.out.println(A / B);
System.out.println(A % B);
}
Output: 30 -10 200 0 10
}
36
Assignment Operators in Java

• An Assignment Operator is an operator used to assign a new


value to a variable. Assume A = 10 and B = 20 for the below
table. public class JavaOperators {
public static void main(String[]
args) {
int a = 10;
int b=20;
int c;
System.out.println(c = a); //
Output =10
System.out.println(b += a);//
Output=30
System.out.println(b -= a);//
Output=20
System.out.println(b *= a);//
Output=200
System.out.println(b /= a);//
37
Relational Operators in Java

• These operators compare the values on either side of them and


public class JavaOperators {
decide the relation among them. Assume A = 10 and B = 20.
public static void main(String[]
args) {
int a = 10;
int b=20;
System.out.println(a == b); //
returns false because 10 is not equal
to 20
System.out.println(a != b); //
returns true because 10 is not equal
to 20
System.out.println(a > b); // returns
false
System.out.println(a < b); // returns
true
System.out.println(a >= b); //
returns false
System.out.println(a <= b); // 38
returns true }}
Logical Operators in Java

• The following are the Logical operators present in Java:

public class JavaOperators {


public static void main(String[]
args) {
int a = 10;
System.out.println(a<10 & a<20);
//returns false
System.out.println(a<10 ||
a<20); //returns true
System.out.println(!(a<10 &
a<20)); //returns true
}
}
39
Unary Operator in Java

• Unary operators are the one that needs a single operand and
are used to increment a value, decrement or negate a value.
public class JavaOperators {
public static void
main(String[] args) {
int a = 10;
boolean b=true;
System.out.println(a++);
//returns 11
System.out.println(++a);
System.out.println(a--);
System.out.println(--a);
System.out.println(!b); // 40
Bitwise Operator in Java
• Bitwise operations directly manipulate bits. In all computers,
numbers are represented with bits, a series of zeros and ones.
In fact, pretty much everything in a computer is represented by
bits. Assume that A = 10 and B = 20 for the below table.
public class JavaOperators {
public static void main(String[]
args) {
int a = 58; //111010
int b=13; //1101
System.out.println(a&b);
//returns 8 = 1000
System.out.println(a|b);
//63=111111
System.out.println(a^b);
//55=11011
System.out.println(~a); //-59 41
Ternary Operators in Java

• The ternary operator is a conditional operator that decreases the


length of code while performing comparisons and conditionals.
This method is an alternative for using if-else and nested if-else
public class
statements. The order of execution for this operator is JavaOperators
from left to {
public static void
right.
(Condition) ? (Statement1) : (Statement2);
main(String[] args) {
•Condition: It is the expression to be evaluated which returns a boolean
value. int a = 20, b = 10, c = 30,
•Statement 1:It is the statement to be executed if the condition results in a res;
true state. res = ((a > b) ? (a > c)? a:
•Statement 2:It is the statement to be executed if the condition results in a c: (b > c)? b: c);
false state. System.out.println("Max of
three numbers = "+ res);
}
}
Output — Max of three numbers = 30
42
Shift Operators in Java

• Shift operators are used to shifting the bits of a number left or


right, thereby multiplying or dividing the number. There are three
different types of shift operators, namely left shift operator()<<,
signed right operator(>>) and unsigned right shift operator(>>>).
numbershift_op number_of_places_to_shift;

public class JavaOperators {


public static void main(String[] args) {
int a=58;
System.out.println(a<<2); //232=11101000
System.out.println(a>>2); //returns 14=1110
System.out.println(a>>>2); //returns 14
}
}
43
Operator Precedence in Java

• Unary Operators
++ – – ! ~ • Bitwise AND
&
• Multiplicative
* /% • Bitwise XOR
^
• Additive
+ – • Bitwise OR Logical AND
&&
• Shift
<< >> >>> • Logical OR
||
• Relational
> >= < <= • Ternary
?:
• Equality
== != • Assignment
• = += -= *= /= %= > >= < <= &= ^= |=
|

44
Data Types in Java

• Data types specify the different sizes and values that can
be stored in the variable. There are two types of data types
in Java:
1. Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

45
46
• There are 8 types of primitive data types:
• boolean data type Data Type Default Value Default size
• byte data type boolean false 1 bit

• char data type char '\u0000' 2 byte


byte 0 1 byte
• short data type
short 0 2 byte
• int data type int 0 4 byte
• long data type long 0L 8 byte
• float data type float 0.0f 4 byte
• double data type double 0.0d 8 byte

47
Boolean Data Type
• The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
Boolean one = false
Byte Data Type
• The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
• The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example:
byte a = 10, byte b = -20

48
Short Data Type
• The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
• The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.
• Example:
short s = 10000, short r = -5000
• Int Data Type
• The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
• The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
int a = 100000, int b = -200000

49
Long Data Type
• The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63
-1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when
you need a range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type
• The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f

50
Double Data Type
• The double data type is a double-precision 64-bit IEEE 754 floating
point. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3
• Char Data Type
• The char data type is a single 16-bit Unicode character. Its
value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'
51
If, If..else Statement in Java

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

52
Output??

53
Switch Case statement in Java with example

54
Switch Case Example

55
Switch with Break :

56
Important for Switch (For MCQ )
Few points about Switch Case
Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer
value after case keyword. Also, case doesn’t need to be in an ascending order
always, you can specify them in any order based on the requirement.
Use characters in switch case.
Nesting of switch statements are allowed, which means you can have switch
statements inside another switch.

57
THANKS
58

You might also like