0% found this document useful (0 votes)
2 views35 pages

Unit-1_Java

This document provides an introduction to Java, covering its features, development tools like JDK and JRE, and the Java Virtual Machine (JVM). It highlights Java's properties such as simplicity, object-oriented design, portability, security, and multithreading capabilities. Additionally, it compares Java with C++, detailing differences in platform dependence, inheritance, and support for various programming constructs.

Uploaded by

salonisingh58494
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)
2 views35 pages

Unit-1_Java

This document provides an introduction to Java, covering its features, development tools like JDK and JRE, and the Java Virtual Machine (JVM). It highlights Java's properties such as simplicity, object-oriented design, portability, security, and multithreading capabilities. Additionally, it compares Java with C++, detailing differences in platform dependence, inheritance, and support for various programming constructs.

Uploaded by

salonisingh58494
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/ 35

Unit 1.

Introduction to Java

• Java is a multi-platform, object-oriented, and network-centric language. •


Java is a programming language and computing platform first released by
Sun Microsystems in 1995.

Java Development kit (JDK)


• JDK is a software development environment used for making applets
and Java applications.
• The full form of JDK is Java Development Kit.
• Java developers can use it on Windows, macOS, Solaris, and Linux. JDK
helps them to code and run Java programs. It is possible to install more
than one JDK version on the same computer.

Why use JDK?


Here are the main reasons for using JDK:

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

Java Virtual Machine (JVM):


• Java Virtual Machine (JVM) is an engine that provides a runtime
environment to drive the Java Code or applications.
• It converts Java bytecode into machine language.
• JVM is a part of the Java Run Environment (JRE). In other programming
languages, the compiler produces machine code for a particular system.
However, the Java compiler produces code for a Virtual Machine known
as Java Virtual Machine.

Why JVM?
Here are the important reasons of using JVM:

• JVM provides a platform-independent way of executing Java source


code.
• It has numerous libraries, tools, and frameworks.
• Once you run a Java program, you can run on any platform and save lots
of time.
Unit 1. Introduction to Java

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

Java Runtime Environment (JRE)


JRE is a piece of software that is designed to run other software. It contains the
class libraries, loader class, and JVM. In simple terms, if you want to run a Java
program, you need JRE. If you are not a programmer, you don’t need to install
JDK, but just JRE to run Java programs.

Why use JRE?


Here are the main reasons of using JRE:

• 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

1.1 Properties of Java


Simple

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

Java Byte code can be carried to any platform. No implementation dependent


features. Everything related to storage is predefined, example: size of primitive
data types.

Platform independent

• Unlike other programming languages such as C, C++ etc which are


compiled into platform specific machines. Java is guaranteed to be write
once, run-anywhere language.
• On compilation Java program is compiled into bytecode. This bytecode is
platform independent and can be run on any machine, plus this bytecode
format also provide security. Any machine with Java Runtime
Environment can run Java Programs.

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

Java makes an effort to eliminate error prone codes by emphasizing mainly on


compile time error checking and runtime checking. But the main areas which
Java improved were Memory Management and mishandled Exceptions by
introducing automatic Garbage Collector and Exception Handling.

Architecture neutral

Compiler generates bytecodes, which have nothing to do with a particular


computer architecture, hence a Java program is easy to interpret on any
machine.

Interpreted
Unit 1. Introduction to Java

High Performance

Java is an interpreted language, so it will never be as fast as a compiled


language like C or C++. But, Java enables high performance with the use of
just-in-time compiler.

Multithreaded

Java multithreading feature makes it possible to write program that can do


many tasks simultaneously. Benefit of multithreading is that it utilizes same
memory and other resources to execute multiple threads at the same time, like
While typing, grammatical errors are checked along.

Distributed

Java is also a distributed language. Programs can be designed to run on


computer networks. Java has a special class library for communicating using
TCP/IP protocols. Creating network connections is very much easy in Java as
compared to C/C++.

1.2 Comparison of java with C++


Comparison C++ Java
Index

Platform C++ is platform-dependent. Java is platform-independent.


independent

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.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can
be achieved by using interfaces
in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You Java supports pointer internally.


can write a pointer program However, you can't write the
in C++. pointer program in java. It
means java has restricted
pointer support in java.

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.

Unit 1. Introduction to Java


Call by Value C++ supports both call by Java supports call by value only.
and Call by value and call by reference. There is no call by reference in
reference java.

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.

Documentati C++ doesn't support Java supports documentation


on comment documentation comments. comment (/** ... */) to create
documentation for java source
code.

Virtual C++ supports virtual keyword Java has no virtual keyword. We


Keyword so that we can decide can override all non-static
whether or not to override a methods by default. In other
function. words, non-static methods are
virtual by default.

unsigned C++ doesn't support >>> Java supports unsigned right


right shift operator. shift >>> operator that fills zero
>>> at the top for the negative
numbers. For positive numbers,
it works same like >> operator.

Inheritance C++ always creates a new Java always uses a single


Tree inheritance tree. inheritance tree because all
classes are the child of the
Object class in Java. The Object
class is the root of the
inheritance tree in java.
Unit 1. Introduction to Java
Hardware C++ is nearer to hardware. Java is not so interactive with
hardware.

Object C++ is an object-oriented Java is also an object oriented


oriented language. However, in the C language. However, everything
language, a single root (except fundamental types) is
hierarchy is not possible. an object in Java. It is a single
root hierarchy as everything
gets derived from
java.lang.Object.

1.3 Java Compiler, Java Interpreter


Java Compiler
• A compiler in Java is a computer program that is used for compiling Java
programs. It is platform-independent. It converts (translates) source code
(.java file) into bytecode (.class file).

• In other words, the compiler (javac.exe) generates bytecode during the


compilation process.

• A bytecode is a binary code that is understood and interpreted by Java


Virtual Machine (JVM) on the underlying operating system. It is not
similar to machine code.

• It is unreadable by humans because it is composed of numbers that are


the only language that computers understand.

• Java compiler can be activated by using “Javac.exe” command from the


command prompt. Some of the compiler options are as follows:
• -help: Display all the compiler option.
• -version: Returns the compiler version.
• -verbose: Output compiler messages.

Unit 1. Introduction to Java


• –deprecation:
Identify retired APIs.
• –nowarn: Generate no warnings.

The compiler options are case-sensitive.

Unit 1. Introduction to Java


Unit 1. Introduction to Java
Java Interpreter
• The Java interpreter converts the Java bytecode (.class file) into the code
understand by the operating system.
• Java interpreter is a computer program (system software) that implements
the JVM. It is responsible for reading and executing the program. It is
designed in such a way that it can read the source program and translate
the source code instruction by instruction.
• It converts the high-level program into assembly language (machine
language).
Unit 1. Introduction to Java

How does the Java interpreter work?


• To convert the byte code into machine code, we deploy the .class file on
the Java Virtual Machine (JVM).
• The JVM converts that code into machine code using the Java interpreter.
The JVM uses the interpreter at runtime, after that it execute the code on
the host machine.

1.4 Identifier, Literals, Operators, Variables, Keywords,


Data Types
Identifier
• Identifiers in Java are symbolic names used for identification. They can be
a class name, variable name, method name, package name, constant
name, and more.
• In Java, There are some reserved words that cannot be used as an
identifier.

Rules for Identifiers in Java

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

o An identifier should not contain a number at the starting. For example,


123javatpoint is an invalid identifier.
o An identifier should be of length 4-15 letters only. However, there is no
limit on its length. But, it is good to follow the standard conventions. o We
can't use the Java reserved keywords as an identifier such as int, float,
double, char, etc. For example, int double is an invalid identifier in Java. o An
identifier should not be any query language keywords such as SELECT,
FROM, COUNT, DELETE, etc.

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

public class Test {


public static void main(String[] args)
{
// decimal-form literal
int a = 101;
// octal-form literal
int b = 0100;
// Hexa-decimal form literal
int c = 0xFace;
// Binary literal
int d = 0b1111;

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

➢ Char literal as Integral literal: we can specify char literal as


integral literal, which represents the Unicode value of the
character, and that integral literal can be specified either in
Decimal, Octal, and Hexadecimal forms. But the allowed range is 0
to 65535.
char ch = 062;
➢ Unicode Representation: We can specify char literals in Unicode
representation ‘\uxxxx’. Here xxxx represents 4 hexadecimal
numbers.
char ch = '\u0061';// Here /u0061 represent a.
➢ Escape Sequence: Every escape character can be specified as
char literals.
char ch = '\n';
Example:
// Java program to illustrate the application of char literals

public class Test {


public static void main(String[] args)
{
// single character literal within single quote
char ch = 'a';
// It is an Integer literal with octal form
char b = 0789;
// Unicode representation
char c = '\u0061';

System.out.println(ch);
System.out.println(b);
System.out.println(c);

// Escape character literal


System.out.println("\" is a symbol");
}
}

• String literals
Any sequence of characters within double quotes is treated as String literals.
String s = "Hello";

Unit 1. Introduction to Java


String literals may not contain unescaped newline or linefeed characters.
However, the Java compiler will evaluate compile-time expressions, so the
following String expression results in a string with three lines of text:
Example:
String text = "This is a String literal\n"
+ "which spans not one and not two\n"
+ "but three lines of text.\n";
// Java program to illustrate the application of String literals

public class Test {


public static void main(String[] args)
{
String s = "Hello";

// If we assign without "" then it treats


// as a variable and causes compiler error
String s1 = 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

public class Test {


public static void main(String[] args)
{
boolean b = true;
boolean c = false;
boolean d = 0;
boolean b = 1;

Unit 1. Introduction to Java


System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}

Operators
Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift Shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^
bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Unit 1. Introduction to Java

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 {

Unit 1. Introduction to Java


public String g; // Declared Instance Variable

public GFG()
{ // Default Constructor

this.g = "Archana"; // initializing Instance Variable }


//Main Method
public static void main(String[] args)
{

// 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 {

public static String g = "Archana"; //Declared static variable


public static void main (String[] args) {

//g variable can be accessed without object creation


System.out.println("Geek Name is : "+GFG.g);
}
}

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

Assert Default Goto public Try

Boolean Do If Static throws

break Double implements strictfp Package

byte Else import super Private

case Enum Interface Short switch

Catch Extends instanceof return void

Char Final Int synchronized volatile

Unit 1. Introduction to Java


class Finally long throw Date

const Float Native This while

Data Types

1.5 Branching: If – Else, Switch


If – Else
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
How Does It Work?
Unit 1. Introduction to Java

When the 'if-else' statement is encountered, the condition within the


parentheses is evaluated. If the condition evaluates to true, the block of code
inside the 'if' block is executed. However, if the condition evaluates to false, the
block of code inside the 'else' block is executed. It allows the program to take
different paths based on the outcome of the condition.
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is
true.
Syntax:
if(condition){
//code to be executed
}

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");
}
}
}

Java if-else Statement


Unit 1. Introduction to Java

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.

public class IfElseExample {


public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}

Java if-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
Unit 1. Introduction to Java
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A
gr ade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;

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!");
}
}
}

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.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Unit 1. Introduction to Java
Example:
//Java Program to demonstrate the use of Nested If
Statement. public class JavaNestedIfExample {

public static void main(String[] args) {


//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood"); }

}
}}

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

Unit 1. Introduction to Java


int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}

1.6 Looping: While, Do-while, For


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.
while (condition){
//code to be executed
Increment / decrement statement
Unit 1. Introduction to Java

}
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
}}

Unit 1. Introduction to Java


//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
//A Java program to demonstrate the use of labeled for
loop public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}

1.7 Type Casting


• Type casting is nothing but assigning a value of one primitive data type to
another.
Unit 1. Introduction to Java

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

In Java, there are two types of casting:

• Widening Casting (automatically): converting a smaller type to a larger


type size
byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually): converting a larger type to a smaller size


type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
• Widening casting is done automatically when passing a smaller size type to
a larger size type:
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

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

Unit 1. Introduction to Java


System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

You might also like