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

B.SC Sem - 5 Java I Unit

The document provides an overview of Java programming, including its history, features, and terminology such as Java Virtual Machine (JVM) and Java Development Kit (JDK). It outlines the advantages of Java's platform independence, object-oriented nature, and security features, as well as the types of applications that can be developed using Java. Additionally, it discusses Java's naming conventions and the structure of a Java program, emphasizing the importance of documentation and comments.

Uploaded by

babaforever786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views32 pages

B.SC Sem - 5 Java I Unit

The document provides an overview of Java programming, including its history, features, and terminology such as Java Virtual Machine (JVM) and Java Development Kit (JDK). It outlines the advantages of Java's platform independence, object-oriented nature, and security features, as well as the types of applications that can be developed using Java. Additionally, it discusses Java's naming conventions and the structure of a Java program, emphasizing the importance of documentation and comments.

Uploaded by

babaforever786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

B.

sc (SEM V) PROGRAMMING IN JAVA

UNIT -1
Introduction to Java
 JAVA was developed by James Gosling at Sun Microsystems in the year 1991, later
acquired by Oracle Corporation.
 It is a simple programming language. Java makes writing, compiling, and debugging
programming easy. It helps to create reusable code and modular programs.
 Java is a class-based, object-oriented programming language and is designed to have as few
implementation dependencies as possible.
 A general-purpose programming language made for developers to write once run anywhere
that is compiled Java code can run on all platforms that support Java. Java applications are
compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is
similar to c/c++.

History
It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick Naughton, a
team of Sun engineers known as the Green team initiated the Java language in 1991. Sun Microsystems
released its first public implementation in 1996 as Java 1.0.

James Gosling in 1995 developed Java, who is known as the Father of Java. Currently, Java is used in
mobile devices, internet programming, games, e-business, etc. Initially it is name as OAK which is a
tree name.later on it is named as java

Java Terminology
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases
of a program. They are written, compile and run the program.

● Writing a program is done by a java programmer


● The compilation is done by the JAVAC compiler which is a primary Java compiler included in the
Java development kit (JDK). It takes Java program as input and generates bytecode as output.
● In the Running phase of a program, JVM executes the bytecode generated by the
compiler.
The function of Java Virtual Machine is to execute the bytecode produced by the compiler. Every
Operating System has a different JVM but the output they produce after the execution of bytecode is
the same across all the operating systems. This is why Java is known as a platform- independent
language.

2. Bytecode in the Development process: The Javac compiler of JDK compiles the java source code
into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the
bytecode, a disassembler like javap can be used.

1
B.sc (SEM V) PROGRAMMING IN JAVA
3. Java Development Kit(JDK): While we were using the term JDK, when we learn about bytecode
and JVM . So, as the name suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program
to execute in java, we need to install JDK on our computer in order to create, compile and run the
java program.

Q.Explain Features of java


Java has become a popular and useful programming language because of its excellent features, which
play a very important role in contributing to the popularity of this language. The Java features are
called “Java BuzzWords”.

Sun MicroSystems officially describes Java with the following list of features:
● Simple and Familiar
● Compiled and Interpreted
● Platform Independent
● Portable
● Architectural Neutral
● Object-Oriented
● Robust
● Secure
● Distributed
● Multi-threaded and Interactive
● High Performance
● Dynamic and Extensible
1. Simple and Familiar
Java is simple because:
Its coding style is very clean and easy to understand. It removes complexity because it doesn’t use
complex and difficult features of other languages like C and C++, which are as follows:

● Concept of Explicit Pointers


● Storage classes
● Preprocessors and header files
● Multiple Inheritance
● Operator Overloading
● Goto Statements
Java programming includes Automatic Garbage Collection, in which there is no need to remove
the unreferenced objects explicitly.

Java is familiar because:


 It has a base of familiar languages like C and C++ and contains many features of these
languages.
2
B.sc (SEM V) PROGRAMMING IN JAVA
 It removes the drawbacks, complexities and confusing elements of C/C++. So if you have good
knowledge of C/C++, you will find Java familiar and easy to understand.

2. Compiled and Interpreted


 Usually, a computer language can be either compiled or interpreted. Java integrates the power
of Compiled Languages with the flexibility of Interpreted Languages.
 Java compiler (javac) compiles the java source code into the bytecode.
 Java Virtual Machine (JVM) then executes this bytecode which is executable on many
operating systems and is portable.

The diagram below shows the above process:

3.Platform Independent
● The most significant feature of Java is that it provides platform independence which leads
to a facility of portability, which ultimately becomes its biggest strength.
● Being platform-independent means a program compiled on one machine can be
executed on any machine in the world without any change.
● Java achieves platform independence by using the concept of the BYTE code.
● In Java the compiler converts the source code into an intermediate code called the byte code
and this byte code is further translated to machine-dependent form by another layer of
software called JVM (Java Virtual Machine).
Therefore, JVM can execute bytecode on any platform or OS on which it is present, regardless of the
fact that on which machine the bytecode was generated.

This is where the “Write Once, run anywhere” (WORA) slogan for Java comes in, which means that
we can develop applications on one environment (OS) and run on any other environment without
doing any modification in the code.

3
B.sc (SEM V) PROGRAMMING IN JAVA
4.Portable
● Java is “portable” refers to the SE (Standard Edition) version. The portability actually
comes from architecture-neutrality.
● Java programs portable among different platforms such as Windows, Unix, Solaris, and
Mac.Any changes and updates made in Operating Systems, Processors and System resources
will not enforce any changes in Java programs.
5.Architectural Neutral
This buzzword means that the program written on one platform or OS is independent of other
platforms or environments and can run on any other Operating System without recompiling them.

6.Object-Oriented
Java strongly supports the concepts of Object-Oriented Programming due to which it is called a pure
object oriented language.

Java supports major Object-Oriented programming features like Encapsulation, Abstraction, and
Inheritance.

7.Robust
● Java is robust as it is capable of handling run-time errors, supports automatic garbage
collection and exception handling, and avoids explicit pointer concept.
● Java has a strong memory management system.
● It helps in eliminating errors as it checks the code during both compile and runtime.
8. Secure
● Security is an important issue for any programming language as there is a threat of
malicious activities and viruses.
● Java supports access modifiers to check memory access and also ensures that no
viruses enter an applet.

● Java is a more secure language as compared to C/C++, as it does not allow a programmer to
explicitly create pointers. Thus in Java, we can not gain access to a particular variable if we do not
initialize it properly.
9.Distributed
● Java is distributed because it encourages users to create distributed applications.
● In Java, we can split a program into many parts and store these parts on different
4
B.sc (SEM V) PROGRAMMING IN JAVA
computers. A Java programmer sitting on a machine can access another program
running on the other machine.
● This feature in Java gives the advantage of distributed programming, which is very helpful
when we develop large projects. Java helps us to achieve this by providing the concept of
RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans).
● Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as
HTTP and FTP, which makes creating network connections much easier than in C/C++.
● It also enables multiple programmers at many locations to work together on a single
project.
10. Multi-threaded and Interactive
● A thread is an independent path of execution within a program, executing concurrently.
Multithreaded means handling multiple tasks simultaneously or executing multiple portions
(functions) of the same program in parallel.
● The code of java is divided into smaller parts and Java executes them in a sequential and timely
manner.
Advantages:
● The main advantage of multithreading is that the maximum utilization of resources is
possible.
● It doesn’t occupy memory for each thread. It shares a common memory area.
● There is no need to wait for the application to finish one task before beginning another one.
● There is a decreased cost of maintenance. Also, It is time-saving.
● It improves the performance of complex applications.

● Java is interactive because its code supports effective CUI (Character User Interface) and GUI
(Graphical User Interface) programs. It greatly improves the interactive performance of
graphical applications.
11. High Performance
● The performance of Java is impressive for an interpreted language because of its
intermediate bytecode.
● Java provides high performance with the use of “JIT – Just In Time compiler”, in which the
compiler compiles the code on-demand basis, that is, it compiles only that method which is
5
B.sc (SEM V) PROGRAMMING IN JAVA
being called. This saves time and makes it more efficient.
● Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine can
execute them much faster.
12. Dynamic and Extensible
● Java is dynamic and extensible means with the help of OOPs, we can add classes and add
new methods to classes, creating new classes through subclasses. This makes it easier for
us to expand our own classes and even modify them.
● Java gives the facility of dynamically linking new class libraries, methods, and objects. It is
highly dynamic as it can adapt to its evolving environment.
● Java even supports functions written in other languages such as C and C++ to be written in Java
programs. These functions are called “native methods”. These methods are dynamically linked
at runtime.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These
are traditional software that we need to install on every machine. Examples of standalone application
are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is
used for creating enterprise applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.

Q.What are Java Platforms / Editions


There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner
classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)


It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on
top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
6
B.sc (SEM V) PROGRAMMING IN JAVA
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Java Version History
Many java versions have been released till now. The current stable release of Java is Java SE 10.
 JDK Alpha and Beta (1995)
 JDK 1.0 (23rd Jan 1996)
 JDK 1.1 (19th Feb 1997)
 J2SE 1.2 (8th Dec 1998)
 J2SE 1.3 (8th May 2000)
 J2SE 1.4 (6th Feb 2002)
 J2SE 5.0 (30th Sep 2004)
 Java SE 6 (11th Dec 2006)
 Java SE 7 (28th July 2011)
 Java SE 8 (18th Mar 2014)
 Java SE 9 (21st Sep 2017)
 Java SE 10 (20th Mar 2018)
 Java SE 11 (September 2018)
 Java SE 12 (March 2019)
 Java SE 13 (September 2019)
 Java SE 14 (Mar 2020)
 Java SE 15 (September 2020)
 Java SE 16 (Mar 2021)
 Java SE 17 (September 2021)
 Java SE 18 (to be released by March 2022)
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release
in March month and an odd version released in September month.

Tools Will Need to java


● will need a Pentium 200-MHz
● computer with a minimum of 64 MB of RAM (128 MB of RAM recommended). will
also need the following softwares:
● Linux 7.1 or Windows xp/7/8 operating system
● Java JDK 8
● Microsoft Notepad or any other text editor

7
B.sc (SEM V) PROGRAMMING IN JAVA
Q.Explain about Naming Convention?

Hungarian Notation:

Hungarian Notation is the naming convention followed by SUN (Stanford University Network) micro
system to develop their predefined classes, interfaces, methods and data members.

Hungarian rule for Class or Interface:


If a class object interface contains more than one word then we must write all the first letters must be
capital.

For example:
System, NumberFormatException, Array IndexOutOfBoundException
Hungarian rule for Method:
If a method name contains more than one word then first word letter is small and rest of the words
first letters must be capital.

For example:
println (), actionPerformed (), adjustmentValueChanged ()
Hungarian rule for Data Members:
All the data members are the predefined classes and interfaces must be represented used as capital
letters.

For example:
PI, MAX_VALUE, and MIN_VALUE
All the data members in the predefined classes and interfaces are belongs to public static
final XXX data members. XXX represents data type, variable name and variable value. Every final
data member must belong to static data member but reverse may or may not be applicable.
Q.Explain Structure of Java Program
Java is an object-oriented programming, platform-independent, and secure programming language
that makes it popular. Using the Java programming language, we can develop a wide variety of
applications.

8
B.sc (SEM V) PROGRAMMING IN JAVA

Documentation section
The documentation section is an important section but optional for a Java program. It includes basic
information about a Java program. The information includes the author's name, date of creation,
version, program name, company name, and description of the program. It improves the readability of
the program. Whatever we write in the documentation section, the Java compiler ignores the
statements during the execution of the program. To write the statements in the documentation
section, we use comments. The comments may be single-line, multi-line, and documentation
comments.

Single-line Comment: It starts with a pair of forwarding slash (//). For example
//First Java Program
Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
For example:

/*It is an example of

multiline comment*/

Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this section, we
declare the package name in which the class is placed. Note that there can be only one package
statement in a Java program. It must be defined before any class and interface declaration. It is
necessary because a Java class can be placed in different packages and directories based on the
module they are used. For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name.

package p1;

Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class of a
particular package, we need to import that class. The import statement represents the class stored in
the other package. We use the import keyword to import the class. It is written before the class
declaration and after the package statement. We use the import statement in two ways, either import
a specific class or import all classes of a particular package. In a Java program, we can use multiple
import statements.

For example:
import java.util.Scanner; //it imports the Scanner class only import

java.util.*; //it imports all the class of the java.util package Interface

9
B.sc (SEM V) PROGRAMMING IN JAVA
Section

It is an optional section. We can create an interface in this section if required. We use the interface
keyword to create an interface. An interface is a slightly different from the class. It contains only
constants and method declarations. Another difference is that it cannot be instantiated. We can
use interface in classes by using the implements keyword. An interface can also be used with other
interfaces by using the extends keyword. For example:

interface car

void start();

void stop();

}
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we cannot
create any Java program. A Java program may conation more than one class definition. We use the
class keyword to define the class. The class is a blueprint of a Java program. It contains information
about user-defined methods, variables, and constants. Every Java program has at least one class that
contains the main() method.

For example:
class Student //class definition

}
Class Variables and Constants
In this section, we define variables and constants that are to be used later in the program. In a Java
program, the variables and constants are defined just after the class definition. The variables and
constants store values of the parameters. It is used during the execution of the program. We can also
decide and define the scope of variables by using the modifiers. It defines the life of the variables.

For example:
class Student //class definition
{
String sname; //variable

int id;

double percentage;

}
10
B.sc (SEM V) PROGRAMMING IN JAVA

Main Method Class


In this section, we define the main() method. It is essential for all Java programs. Because the execution
of all Java programs starts from the main() method. In other words, it is an entry point of the class. It
must be inside the class. Inside the main method, we create objects and call the methods. We use the
following statement to define the main() method:

public static void main(String args[])


{
}
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
Methods and behavior
In this section, we define the functionality of the program by using the methods. The methods are the
set of instructions that we want to perform. These instructions execute at runtime and perform the
specified task. For example:

public class Demo //class definition


{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to java");
}
}
Demo d;

d.display();

}
}
Output
Welcome to java
Creating Hello World Example
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java"); } }
11
B.sc (SEM V) PROGRAMMING IN JAVA

Save the above file as Simple.java.


To compile: javac

Simple.java To

execute:

java Simple

Output:

Hello Java

Parameters used in First Java Program


In the above example
class keyword is used to declare a class in Java.
public keyword is an access modifier that represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main() method is executed by the JVM, so it doesn't require creating an object to invoke the main()
method. So, it saves memory.

void is the return type of the method. It means it doesn't return any value. main

represents the starting point of the program.

String[] args or String args[] is used for command line argument.


System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.
Charecter set of java
Java language uses the character sets as the building block to form the basic elements such as
identifiers, variables, array, etc in the program. These are as follows:

Letters: Both lowercase (a, b, c, d, e, etc. ) and uppercase (A, B, C, D, E, etc.) letters.
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Special symbols: _, (, ), {, }, [, ], +, -, *, /, %, !, &, |, ~, ^, <, =, >, $, #, ?, Comma (,), Dot (.), Colon (:),
Semi-colon (;), Single quote (‘), Double quote (“), Back slash (\).

White space: Space, Tab, New line.

Explain about Java tokens?


The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens.
These tokens are separated by the delimiters. It is useful for compilers to detect errors.

12
B.sc (SEM V) PROGRAMMING IN JAVA
Java supports 5 types of tokens which are:

● Keywords
● Identifiers
● Literals
● Operators
● Special Symbols
Keywords
Keywords in Java are predefined or reserved words that have special meaning to the Java compiler.
Each keyword is assigned a special task or function and cannot be changed by the user. You cannot use
keywords as variables or identifiers as they are a part of Java syntax itself. A keyword should always be
written in lowercase as Java is a case sensitive language. Java supports various keywords, some of them
are listed below:

The list of the reserved keyword is as follows:


a) Data Type: Java language has reserved eight words as keywords for data types that are as
follows:

● byte
● short
● int
● long
● float
● double
● char
● boolean
b) Access Modifiers: There are three reserved words as keywords for access modifiers by Java
language. They are as follows:
13
B.sc (SEM V) PROGRAMMING IN JAVA
● private
● protected
● public
These keywords are called access modifier keywords.
c) Control Statement: There are ten reserved words as keywords for the control statement by Java
language. They are as:

● else
● switch
● case
● default
● for
● while
● do
● continue
● break
● goto [reserved but not in used]
● if
d) Object and Classes: There are seven reserved keywords for classes and objects by Java
language. They are as follows:

● class
● interface
● extends
● implements
● this
● super
● new
e) Modifiers: There are eight modifier keywords reserved in the Java language. These
keywords are also called non-access modifier keywords. They are as follows:
● static
● abstract
● synchronized
● volatile
● native
● transient
● strictfp
● final
f) Exceptions: There are five exception keywords that are reserved by Java language. They are as:
14
B.sc (SEM V) PROGRAMMING IN JAVA
● try
● catch
● finally
● throw
● throws
g) Package: Java language has included two reserved keywords for a package that is as follows:

● package
● import
h) Miscellaneous keywords:
● return
● const (*)
● instanceof
● void
● assert
● default
● enum
The keywords const and goto are reserved but not used. In addition to these keywords, Java reserves
the following: null, true, and false.

Identifier
Java Identifiers are the user-defined names of variables, methods, classes, arrays, packages, and
interfaces. Once you assign an identifier in the Java program, you can use it to refer the value
associated with that identifier in later statements.
There are some rules which you must follow while naming the identifiers such as:
● Identifiers must begin with a letter, dollar sign or underscore.
● Apart from the first character, an identifier can have any combination of characters.
● Identifiers in Java are case sensitive.
● Java Identifiers can be of any length.
● Identifier name cannot contain white spaces.
● Any identifier name must not begin with a digit but can contain digits within.
● Most importantly, keywords can’t be used as identifiers in Java.

Example:
//Valid Identifiers
$myvariable //correct
_name //correct

Name //correct

Name _of _student //correct


15
B.sc (SEM V) PROGRAMMING IN JAVA
Srudent1name //correct

//Invalid Identifiers

Name student //error

&Name //error

23name //error

switch //error

Studnet's //error

Literals

Literals in Java are similar to normal variables but their values cannot be changed once assigned. In
other words, literals are constant variables with fixed values. These are defined by users and can
belong to any data type. Java supports five types of literals which are as follows:

● Integer
● Floating Point
● Character
● String
● Boolean
Example:
public class sample
{
public static void main(String[] args)
{
int a1 = 112; // Int literal
float a2 = 31.10; // Float literal char

a3 = 'edu' // char literal

String s = "Edureka"; // String literal

boolean value = true; // Boolean literal

System.out.println(a1); //112

System.out.println(a2); //31.40

System.out.println(a3); //edu

System.out.println(s); //Edureka

System.out.println(value); //true } }

16
B.sc (SEM V) PROGRAMMING IN JAVA
Operators
An operator in Java is a special symbol that signifies the compiler to perform some specific
mathematical or non-mathematical operations on one or more operands. Java supports 8 types of
operators. Below I have listed down all the operators, along with their examples:

Operator Examples

Arithmetic+ , – , / , * , %
Unary ++ , – – , !
Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>


Special Symbols
Special symbols in Java are a few characters which have special meaning known to Java compiler and
cannot be used for any other purpose. In the below table I have listed down the special symbols
supported in Java along with their description.

Symbol Description

● Brackets [] These are used as an array element reference and also indicates single and
multidimensional subscripts
● Parentheses() These indicate a function call along with function parameters
● Braces{} The opening and ending curly braces indicate the beginning and end of a block
of code having more than one statement
● Comma ( , ) This helps in separating more than one statement in an expression
● Semi-Colon (;) This is used to invoke an initialization list
● Asterisk (*) This is used to create a pointer variable in Java

Q)Explain Data types in Java


There are majorly two types of languages.
First, one is Statically typed language where each variable and expression type is already known at
compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other
data types.

Example: C, C++, Java.


17
B.sc (SEM V) PROGRAMMING IN JAVA
The other is Dynamically typed languages. These languages can receive different data types over time.

Example: Ruby, Python


Java is statically typed and also a strongly typed language because, in Java, each type of data (such
as integer, character, hexadecimal) is predefined as part of the programming language and all
constants or variables defined for a given program must be described with one of the data types.
Data Types in Java

Q)Explain Variables in Java


 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 effects that memory location.
 In Java, all the variables must be declared before use.

How to declare variables


We can declare variables in java as
Syntax
Dataype variablename ;

18
B.sc (SEM V) PROGRAMMING IN JAVA
Datatype: Type of data that can be stored in this variable.
Variable name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:

Variable Initialization Assigning

value by taking input Datatye

variable name=value;

datatype: Type of data that can be stored in this variable.

variable_name: Name given to the variable.

value: It is the initial value stored in the variable.

different types of variables which are listed as follows:

● Local Variables
● Instance Variables
● Static Variables
Local variables
● 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 variable is
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.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside 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 Instance Variable is not Mandatory. Its default value is 0
19
B.sc (SEM V) PROGRAMMING IN JAVA
● Instance Variable can be accessed only by creating objects.
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 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 Static Variable is not Mandatory. Its default value is 0
● If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The compiler will
replace the object name with the class name automatically.
● If we access the static variable without the class name, the compiler will automatically
append the class name.
Example
class sample
{
// Static variable

static int a;

// Instance variable

int b;

Q.explain about Control Statements in java


Control Statements are used to control the execution flow of the program. There are

three types of control statements:

● Conditional Control Statements


20
B.sc (SEM V) PROGRAMMING IN JAVA
● Looping Control Statements
● Unconditional Control Statements/Jump Statements
Conditional Control Statements
Conditional Control Statements allows the program to select between the alternatives during the
program execution.

They are also called as decision-making statements or selection statements.


1. If statement
It will go inside the block only if the condition is true otherwise, it will not execute the block.
Syntax:
if(condition)
{
// statements
}
//other statements
Flowchart
Example

class IfExample
{
public static void main(String []args)
{
int a=10;

If(a>0)

{
System.out.println(“Value of a is positive");
} } }
Output
Value of a is positive

2. If-Else Statement
If the condition is true then, it will execute the If block. Otherwise, it will execute the Else block.

Syntax
21
B.sc (SEM V) PROGRAMMING IN JAVA
if(condition)
{
// statements
}
else
{
// statements
}
//other statements
Flowchart

Example
class IfElseExample
{
public static void main(String []args)
{
int a=-10;

If(a>0)

{
System.out.println(“Value of a is positive");
}
else
{
System.out.println(“Value of a isnegative");
}}}
Output
Value of a is negative
3. If Else-If statement
If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If block.
Again, if the condition is not met, then it will move to the else block.
if(condition1)
{
// statements
22
B.sc (SEM V) PROGRAMMING IN JAVA
}
else if(condition 2)
{
// statements
}
………..
…………
………...
else if(condition n)
{
//statements
}
else
{
//statements
}
Example
class IfElseIfExample
{
public static void main(String []args)
{
int a=0;

If(a>0)

{
System.out.println(“Value of a is positive");
}
else if(a<0)
{
System.out.println(“Value of a isnegative");
}
else
{
System.out.println(“Value of a is zero");
} } }
Output
Value of a is zero
4. Switch Statement
Switch statement allows program to select one action among multiple actions during the program
execution.
Syntax:
switch (expression)
{
case value1:
23
B.sc (SEM V) PROGRAMMING IN JAVA
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
Based on the argument in the switch statement suitable case value will be selected and executed.

If no matching case found, then the default will be executed.


It is optional to write a break statement at the end of each case statement.
Flow chart

Example
import java.util.Scanner;
public class SwitchExample
{
public static void main(String[] args)
{
int num1, num2;
Scanner s= new Scanner(System.in);
System.out.print("Enter first number:");
num1 = s.nextInt();
System.out.print("Enter second number:");
num2 = s.nextInt();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = s.next().charAt(0);
s.close();
int result ;
switch(operator)
{
case '+':
result= num1 + num2;
24
B.sc (SEM V) PROGRAMMING IN JAVA
break;
case '-':
result = num1 - num2;
break;
case '*':
result= num1 * num2;
break;
case '/':
result = num1 / num2;
break;
/* If user enters any other operator or char apart from
* +, -, * and /, then display an error message to user
*
*/
default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+result);
} }
Output:
Enter first number:40
Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0
Looping Control Statements
These are used to execute a block of statements multiple times. It means it executes the same code
multiple times so it saves code. These are also called Iteration statements.

There are three types of looping control statements:


● For loop
● While loop
● Do-while loop
1. For loop
It executes the code until condition is false.
It is used when number of iterations are known.
Syntax:
for(initialization; condition; increment/decrement)
{
//statements
}
● First step: In for loop, initialization happens first and only one time, which means that the
initialization part of for loop only executes once.
● Second step: Condition in for loop is evaluated on each iteration, if the condition is true then

25
B.sc (SEM V) PROGRAMMING IN JAVA
the statements inside for loop body gets executed. Once the condition returns false, the
statements in for loop does not execute and the control gets transferred to the next
statement in the program after for loop.
● Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
● Fourth step: After third step, the control jumps to second step and condition is re-
evaluated.
Flow chart

Example
class ForExample
{
public static void main(String []args)
{
int a=1;
for(int i=0; i<5; i++)
{
System.out.println(“Value of a is:”+ a); a+
+; // increases value by 1
} } }
Output:
Value of a is:1
Value of a is:2
Value of a is:3
Value of a is:4
Value of a is:5
2. While loop
While loop executes till the condition becomes false.
Syntax:
while(condition)
{
// statements
}
26
B.sc (SEM V) PROGRAMMING IN JAVA
Flowchart

In while loop, condition is evaluated first and if it returns true then the statements inside while loop
execute. When condition returns false, the control comes out of loop and jumps to the next statement
after while loop.

Example
class WhileLoopExample
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
} } }
Output:
10 9 8 7 6 5 4 3 2

3. Do-while loop
When you are using for or while, then it will execute the loop body only if the condition if true.
In do-while loop, it will execute the loop first, then it checks the condition. So, it will execute the loop
atleast once.

It is called exit controlled loop and for ,while loop are called entry controlled loop.
Syntax:
do
{
// statements
}while(condition);
Flowchart

27
B.sc (SEM V) PROGRAMMING IN JAVA

Example Program
class Sample
{
public static void main(String args[])
{
int a = 1;
do
{
System.out.println(“hello”); i+
+;
}while( a<=1 );
}}
Output
Hello
Unconditional Control Statements/Jump Statements
1. break Statement
break is a keyword. It is used within any control statements. It is used to terminate the execution of the
current loop or switch statements.

Syntax: break; or break <label>;


Example Use of break in a while loop
public class BreakExample1
{
public static void main(String args[])
{
int num =0;
while(num<=100)
{
System.out.println("Value of variable is: "+num); if
(num==2)
{
break;
}
num++;
}
System.out.println("Out of while-loop");
}
Output:

28
B.sc (SEM V) PROGRAMMING IN JAVA
Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Outof while-loop
2.continue Statement
continue is a keyword. It is used to continue the execution of the current loop with the next iteration.

Syntax: continue; or continue<label>;


Flowchart

Example: continue statement inside for loop


public class ContinueExample
{
public static void main(String args[])
{
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}
System.out.print(j+" ");
} } }
Output:
012356
Q.Java Virtual Machine (JVM), Difference JDK, JRE & JVM – JVM

Java is a high level programming language. A program written in high level language cannot be run on
any machine directly. First, it needs to be translated into that particular machine language. 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. This makes it easier for compiler as it has to generate byte
code for JVM rather than different machine code for each type of machine. JVM executes the byte
code generated by compiler and produce output. JVM is the one that makes java platform
29
B.sc (SEM V) PROGRAMMING IN JAVA
independent.

So that the primary function of JVM is to execute the byte code produced by compiler. 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. The same thing can
be seen in the diagram below:

JVM Architecture

how JVM works:


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.
30
B.sc (SEM V) PROGRAMMING IN JAVA
JVM Vs JRE Vs JDK
JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual
Machine(JVM), class libraries, and other files excluding development tools such as compiler and
debugger.

Which means you can run the code in JRE but you can’t develop and compile the code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.

JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as
compiler, debugger etc.

Q.Explain Type Casting in Java


Type casting is a way of converting data from one data type to another data type. This process of data
conversion is also known as type conversion or type coercion.

In Java, we can cast both reference and primitive data types. By using casting, data can not be changed
but only the data type is changed.

Note: type casting is not possible for a Boolean data type. Type
casting can be
● Implicit casting.
● Explicit casting.
Implicit casting
This type of conversion is also known as widening casting. It happens automatically when converting
from a narrower range data type to a wider range data type. It also means converting a lower data type
like an int to a higher data type like a double.

Implicit casting takes place under two conditions:


Compatibility of the data types. For example, data types such as numeric are compatible with other
numeric data types, but they are not compatible with boolean, char, or string data types. In the same
way as string is not compatible with a boolean data type.

If the targeted value to be converted has a smaller length e.g. 4 bytes, to a larger data type e.g. 8 bytes.

31
B.sc (SEM V) PROGRAMMING IN JAVA
Implicit casting follows the order of conversion as shown below:
Byte -> Short -> Char -> Int -> Long -> Float -> Double
Example
Here, we will convert an int value to a long value and finally to a double value by using a simple
assignment operator:

public class Main


{
public static void main(String[] args)
{
int a = 20;
long b = a; //implicit casting from int to long data type double c
= b; // implicit casting from long to double data type
System.out.println(a);
System.out.println(b);
System.out.println(c);
} }
Output:
20
20
20.0
Explicit type casting
This type of casting involves assigning a data type of high range to a lower range. This process of
conversion is also referred to as narrowing type casting.
This is done manually as you need to do the casting using the “()” operator. If we fail to do the casting,
a compile-time error will be returned by the compiler.
Explicit casting follows the order of conversion as shown below:
Double -> FLoat -> Long -> Int -> Char -> Short -> Byte
Example
public class Main
{
public static void main(String args[])
{
double d = 57.17;

int i = (int)d; // Explicit casting from long to int data type

System.out.println(d);
System.out.println(i); //fractional part lost
} }
Output:
57.17
57
57
In the example above, we converted the double data type into an int data type. The decimal part of
the value is lost after type casting.
32

You might also like