Unit-1_Java
Unit-1_Java
Introduction to Java
• JDK contains tools required to write Java programs and JRE to execute
them.
• It includes a compiler, Java application launcher, Appletviewer, etc. •
Compiler converts code written in Java into byte code.
• Java application launcher opens a JRE, loads the necessary class, and
executes its main method.
Why JVM?
Here are the important reasons of using JVM:
• JVM comes with JIT (Just-in-Time) compiler that converts Java source
code into low-level machine language. Hence, it runs faster than a
regular application.
• JRE contains class libraries, JVM, and other supporting files. It does not
include any tool for Java development like a debugger, compiler, etc. • It
uses important package classes like math, swing, util, lang, awt, and
runtime libraries.
• If you have to run Java applets, then JRE must be installed in your
system.
Unit 1. Introduction to Java
Java is easy to learn and its syntax is quite simple, clean and easy to
understand. The confusing and ambiguous concepts of C++ are either left
out in Java or they have been re-implemented in a cleaner way.
Eg: Pointers and Operator Overloading are not there in java but were an
important part of C++.
Object-Oriented
In java, everything is an object which has some data and behaviour. Java can be
easily extended as it is based on Object Model. Following are some basic
concept of OOP's.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation
Unit 1. Introduction to Java
Portable
Platform independent
Secured
• When it comes to security, Java is always the first choice. With java secure
features it
• enables us to develop virus free, temper free system.
• Java program always runs in Java runtime environment with almost null
interaction with system OS, hence it is more secure.
Robust
Architecture neutral
Interpreted
Unit 1. Introduction to Java
High Performance
Multithreaded
Distributed
Mainly used for C++ is mainly used for system Java is mainly used for
programming. application programming. It is
widely used in Windows-based,
web-based, enterprise, and
mobile applications.
Unit 1. Introduction to Java
Design Goal C++ was designed for systems Java was designed and created
and applications as an interpreter for printing
programming. It was an systems but later extended as a
extension of the C support network computing. It
programming language. was designed to be easy to use
and accessible to a broader
audience.
Goto C++ supports the goto Java doesn't support the goto
statement. statement.
Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts converted into bytecode at
source code into machine compilation time. The
code so, C++ is platform interpreter executes this
dependent. bytecode at runtime and
produces output. Java is
interpreted that is why it is
platform-independent.
Structure and C++ supports structures and Java doesn't support structures
Union unions. and unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies
on third-party libraries for
thread support.
o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and
underscore(_) or a dollar sign ($). for example, @javatpoint is not a valid
identifier because it contains a special character which is @.
o There should not be any space in an identifier. For example, java tpoint is
an invalid identifier.
Unit 1. Introduction to Java
Literals
• Any constant value which can be assigned to the variable is called
literal/constant.
// Here 100 is a constant/literal.
int x = 100;
• For Integral data types (byte, short, int, long), we can specify literals in 4
ways:-
➢ Decimal literals (Base 10): In this form, the allowed digits are 0-
9.
int x = 101;
➢ Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
➢ Hexa-decimal literals (Base 16): In this form, the allowed digits
are 0-9, and characters are a-f. We can use both uppercase and
lowercase characters as we know that java is a case-sensitive
programming language, but here java is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
➢ Binary literals: From 1.7 onward, we can specify literal value even
in binary form also, allowed digits are 0 and 1. Literals value
should be prefixed with 0b or 0B.
Unit 1. Introduction to Java
int x = 0b1111;
Example:
// Java program to illustrate the application of Integer literals
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
• Floating-Point literal
For Floating-point data types, we can specify literals in only decimal form, and
we cant specify in octal and Hexadecimal forms.
➢ Decimal literals(Base 10): In this form, the allowed digits are 0-
9.
double d = 123.456;
• Char literals
For char data types, we can specify literals in 4 ways:
➢ Single quote: We can specify literal to a char data type as a single
character within the single quote.
char ch = 'a';
Unit 1. Introduction to Java
System.out.println(ch);
System.out.println(b);
System.out.println(c);
• String literals
Any sequence of characters within double quotes is treated as String literals.
String s = "Hello";
System.out.println(s);
System.out.println(s1);
}
}
• Boolean literals
Only two values are allowed for Boolean literals, i.e., true and false.
boolean b = true;
// Java program to illustrate the application of boolean literals
Operators
Operator Type Category Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Variables
Variable in Java is a data container that saves the data values during Java
program execution. Every variable is assigned a data type that designates the
type and quantity of value it can hold. A variable is a memory location name for
the data.
A variable is a name given to a memory location. It is the basic unit of storage
in a program.
• The value stored in a variable can be changed during program
execution.
• A variable is only a name given to a memory location. All the operations
done on the variable affect that memory location. • In Java, all variables
must be declared before use.
Types of Variables in Java
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
Unit 1. Introduction to Java
• 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.
import java.io.*;
class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
2. Instance Variables
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 0.
• Instance variables can be accessed only by creating objects.
import java.io.*;
class GFG {
public GFG()
{ // Default Constructor
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("name is: " + name.geek);
}
}
3. Static Variables
Static variables are also known as class variables.
• These variables are declared similarly as 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 0.
• 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.
Unit 1. Introduction to Java
import java.io.*;
class GFG {
Keywords
• Java reserved keywords are predefined words, which are reserved for any
functionality or meaning.
• We cannot use these keywords as our identifier names, such as class name
or method name. These keywords are used by the syntax of Java for
some functionality. If we use a reserved word as our variable name, it will
throw an error.
abstract Continue for protected transient
Data Types
Example:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
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){
//code if condition is true
}else{
//code if condition is false
}
//A Java Program to demonstrate the use of if-else
statement. //It is a program of odd and even number.
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
Unit 1. Introduction to Java
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
}
}}
Ternary Operator
We can also use ternary operator (? :) to perform the task of if...else statement.
It is a shorthand way to check the condition. If the condition is true, the result
of ? is returned. But, if the condition is false, the result of : is returned.
Example:
public class IfElseTernaryExample {
public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
Unit 1. Introduction to Java
System.out.println(output);
}
}
Switch
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.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
}
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
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.
do{
//code to be executed / loop body
//update statement
}while (condition);
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
For Loop
Unit 1. Introduction to Java
For loops in Java are a fundamental control structure used to repeat a block of
code a specific number of times or iterate through a sequence of values. They
are incredibly useful for tasks that require repetition, such as processing items
in an array, generating repetitive output, or executing a block of code a
predetermined number of times.
The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.
There are the following three types of for loops in Java.
o Simple for Loop
o For-each or Enhanced for Loop
o Labelled for Loop
/Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}}
• When you assign the value of one data type to another, you should be
aware of the compatibility of the data type.
• If they are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not, then they need to be
casted or converted explicitly.
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
• Narrowing casting must be done manually by placing the type in
parentheses in front of the value:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int