You are on page 1of 35

UNIT 1

Program Structure in Java: Introduction, Writing Simple Java Programs, Tokens in Java
Programs, Command Line Arguments, Comments.
Data Types, Variables, and Operators: Introduction, Data Types in Java, Static Variables
and Methods, Attribute Final, Operators.
Control Statements: If Expression, Switch Statement, Loops.

I. Program Structure in Java


1.1 Introduction to Java programming
JAVA was developed by James Gosling at Sun Microsystems Inc in the
year 1991, later acquired by Oracle Corporation. It is a high-level and simple programming
language. Java makes writing, compiling, and debugging programming easy. It helps to create
reusable code and modular programs.
Java is an object-oriented programming language with a built-in application
programming interface (API) that can handle graphical user interfaces (GUI) used to create
applications or applets. Java provides a rich set of APIs apart from being platform
independent.
Java can be used to develop Web applications. Java can also be used to develop
applications for hand-held devices such as Palm and cell phones.
Examples of Java’s Versatility (Applets)

1.1.1 The History of Java


Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first
working version. This language was initially called “Oak,” but was renamed “Java” in 1995.
Sun Microsystems released its first public implementation in 1996 as Java 1.0.
In 1997, Sun Microsystems approached the ISO standards body and later formalized
Java, but it soon withdrew from the process. At one time, Sun made most of its Java
implementations available without charge, despite their proprietary software status. Sun
generated revenue from Java through the selling of licenses for specialized products such as
the Java Enterprise System.
On November 13, 2006, Sun released much of its Java virtual machine as free, open-
source software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code
available under open-source distribution terms.
Many java versions have been released till now. The current stable release of Java is
Java SE 10.

Version Release Date Features

JDK Beta 1995 —

JDK 1.0 January 1996 This is the first stable version.

In this version, added many new library elements, redefined the


way of handling events, and reconfigured most of the libraries of
JDK 1.1 February 1997
1.0 and deprecated some features defined by 1.0. Added inner
class, JavaBeans, JDBC, RMI, JIT (Just In time) compiler.

Added support for many features, such as Swing and Collection


J2SE 1.2 December 1998 Framework. The methods suspend(), resume() and stop() of
Thread class were deprecated.

A very small improvement, as it just improved the development


J2SE 1.3 May 2000
environment.

It added some upgrades such as the new keyword assert, chained


J2SE 1.4 February 2002 exception and a channel-based I/O subsystem. Also added some
feature to the collection framework and the Networking classes.

The significant new features added to this version are – Generics,


Annotation, Autoboxing and Auto-unboxing, Enumeration, for-
J2SE 5.0 September 2004
each, variable-length argument, Static import, Formatted I/O,
Concurrency utilities.
In this version the API libraries and several new packages got
Java SE 6 December 2006 enhanced and offered improvements to the run time. It supports
JDBC 4.0.

Added JVM support for dynamic language, String in the switch,


Java SE 7 July 2011 Automatic resource management in try-statement, support for
underscore in integers, binary integer literals etc…

Java SE 8 March 2014 Added Date and time API, Repeating annotation, JavaFX.

Added Java platform module system update, jshell, XML Catalog,


Java SE 9 September 2017
jlink, and the JavaDB was removed from JDK

Added features are local variable type interface, Application class


Java SE 10 March 2018
data sharing, Garbage collector interface, etc…

Feature added: Dynamic class file loader, HTTP client, and


Java SE 11 September 2018 Transport layer security. JavaFX, Java EE, and CORBA modules
have been removed from JDK.

Added Microbenchmark Suite, JVM Constant API, One AArch64


Java SE 12 March 2019
Port, Default CDS Archives etc.

1.1.2 Java Buzzwords or Features or Characteristics


Simple: - Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++.
Secure: - Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application.
Portable: - Portability is one of the core features of java which enables the java programs to
run on any computer or operating system. For example, an applet developed using java runs on
a wide variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented: - Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented programming
paradigm. The primitive data type’s java also implemented as objects using wrapper classes,
but still, it allows primitive data types to archive high-performance.
Architecture-neutral (or) Platform Independent: - Java has invented to archive "write once;
run anywhere, anytime, forever". The java provides JVM (Java Virtual Machine) to to archive
architectural-neutral or platform-independent. The JVM allows the java program created using
one operating system can be executed on any other operating system.
Robust: - Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage collector), java is
a strictly typed language, it has a strong set of exception handling mechanism, and many more.
Multi-threaded: - Multithreaded Programs handled multiple tasks simultaneously, which was
helpful in creating interactive, networked programs. Java run-time system comes with tools
that support multiprocess synchronization used to construct smoothly interactive systems.
Interpreted: - Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java byte code. The byte code is interpreted to any machine
code so that it runs on the native machine.
High Performance: - Java is faster than other traditional interpreted programming languages
because Java byte code is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed: - Java programming language supports TCP/IP protocols which enable the java
to support the distributed environment of the Internet. Java also supports Remote Method
Invocation (RMI), this feature enables a program to invoke methods across a network.
Dynamic: - Java is a dynamic language. It supports dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.
1.1.3 OOPs Principles
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some concepts:
Object: - Any entity that has state and behavior is known as an object. An Object can be defined
as an instance of a class. For example, a chair, pen, table, keyboard, bike, etc. It can be physical
or logical.
Class: - Collection of objects is called class. It is a logical entity. A class can also be defined
as a blueprint from which you can create an individual object.
Inheritance: - When one object acquires all the properties and behaviors of a parent object, it
is known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism: - If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc. In Java, we use method overloading and method overriding to achieve
polymorphism. Another example can be to speak something; for example, a cat speaks meow,
dog barks woof, etc.
Abstraction: - Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing. In Java, we use abstract class and
interface to achieve abstraction.
Encapsulation: - Binding (or wrapping) code and data together into a single unit are known
as encapsulation. For example, a capsule, it is wrapped with different medicines.
1.1.4 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. So, before diving in depth, it is necessary to understand
the basic structure of Java program in detail.
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 is an example of documentation comment*/
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.
package javatpoint; //where javatpoint is the package name
package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory
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.
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all the class of the java.util package
Interface 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.
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.
class Student //class definition
{
}
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.
public static void main(String args[])
{
}
1.1.5 Creating, Compiling, and Running Programs
Java compiler first converts the source code into an intermediate code,
known as bytecode or virtual machine code. To run the bytecode, we
need the Java Virtual Machie (JVM). JVM exists only inside the
computer memory and runs on top of the Operating System. The
bytecode is not machine specific. The Java interpreter converts the
bytecode into Machine code. The following diagram illustrates the
process of compiling and running Java programs. For compiling the program, the Java compiler
javac is run, specifying the name of the source file on the command line as depicted here:
javac Start.java
The Java compiler creates a file called Start.class containing the bytecode version of
the program. The java interpreter in JVM executes the instructions contained in this
intermediate Java bytecode version of the program. The Java interpreter is called with “java”
at the command prompt.
C:\> java Start
Output: Hello World
Here java command calls the Java interpreter which executes the Start.class(bytecode
of Start.java).

Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code
}
}

Compile Source Code


Byte code (generated by the compiler for JVM i.e., javac Welcome.java
to read and interpret, not for you to understand)

Method Welcome() If compilation errors
0 aload_0 stored on the disk

Bytecode
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return Run Byteode
i.e., java Welcome

Result

If runtime errors or incorrect result


1.2 Writing Simple Java Programs
Now that the basic object-oriented underpinning of Java has been discussed, let’s look
at some actual Java programs. Let’s start by compiling and running the short sample program
shown here.
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
To compile: javac Example.java
To execute: java Example
Output: This is a simple Java program.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which 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 main method is executed by the JVM, so it doesn't require to create 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 is used for command line argument. We will learn it later.
• System.out.println() is used to print statement. Here, System is a class, out is the object
of PrintStream class, println() is the method of PrintStream class.

1.3 Tokens in Java Programs


The tokens are the small building blocks of a Java program that are meaningful to the
Java compiler. 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. Remember that the delimiters are not part of the Java tokens.
token <= identifier | keyword | separator | operator | literal | comment
1.3.1 Types of Tokens
Java token includes the following:
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Comments
1. Keywords: These are the pre-defined reserved words of any programming language. Each
keyword has a special meaning. It is always written in lower case. Java provides the following
keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
2. Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. Remember that the identifier name must be different from the
reserved keywords. There are some rules to declare identifiers are:
• The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
• It should not contain white spaces and special symbols.
• It should not be a keyword of Java.
• It should not be Boolean literal, that is, true or false.
• It should not be null literal. It should not start with a digit but it can start with an
underscore.
Conventions for Writing Names
• Names of packages are completely in lower-case letters such as mypackage, java.lang.
• Names of classes and interfaces start with an upper-case letter.
• Names of methods start with a lower-case character.
• Names of variables should start with a lower-case character.
Some valid identifiers are:
PhoneNumber
PRICE
radius
a
a1
_phonenumber
$circumference
jagged_array
12radius //invalid
3. Literals/Constants: These are values represented by a set of character, digits, etc.
• A literal represents a value which may be of primitive type, String type, or null type.
• The value may be a number (either whole or decimal point number) or a sequence of
characters which is called String literal, Boolean type, etc. A literal is a constant value.
Types of Literals:
a). Integer literals
• Sequences of digits.
• The whole numbers are described by different number systems such as decimal
numbers, hexadecimal numbers, octal numbers, and binary numbers.
• Each number has a different set of digits.
Decimal Integer Literals
• These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
• Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
• These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A,
B, C, D, E, and F.
• The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and f.
• The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
Octal Integer Literals
• These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
• These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
• These are sequences of binary digits.
• Binary numbers have only two digits—0 and 1 and a base 2.
• Examples of such literals are 0b0111001, 0b101, 0b1000, etc
b). Floating point literal
• These are floating decimal point numbers or fractional decimal numbers with base 10.
Examples are 3.14159, 567.78, etc.
c). Boolean literal
• These are Boolean values. There are only two values—true or false.
d). Character literal
• These are the values in characters.
• Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
e). String literal
• These are strings of characters in double quotes. Examples are “Delhi”, “John”, “AA”,
etc.
f). Null literal
• There is only one value of Null Literal, that is, null.
4. Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide. There are eight types of operators in Java, are as
follows:
Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus

Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than
Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
Increment / Decrement Operators:
Operator Description
++ Increment by one
-- Decrement by one
Bitwise Operators:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill
Conditional Operators:
Operator Description
?: Used to construct Conditional expression
5. Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows: separator <= ; | , | . | ( | ) | { | } | [ | ]
• Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the two-
dimensional array.
• Parentheses (): It is used to call the functions and parsing the parameters.
• Curly Braces {}: The curly braces denote the starting and ending of a code block.
• Comma (,): It is used to separate two values, statements, and parameters.
• Assignment Operator (=): It is used to assign a variable and constant.
• Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
• Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
7. Comments: Comments allow us to specify information about the program inside our
Java
8. code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the
following two types of comments:
• Line Oriented: It begins with a pair of forwarding slashes (//).
• Block-Oriented: It begins with /* and continues until it founds */.

1.4 Command Line Arguments


• A Java application can accept any number of arguments from the command line. These
arguments can be passed at the time of running the program.
• The arguments passed from the console can be received in the java program and it can
be used as an input.
• This enables a programmer to check the behavior of a program for different values of
inputs.
• It must be noted that the number of arguments in an array. To ensure this, we can make
use of the length property of the array.
Example 1
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
Example 2 of command-line argument that prints all the values
class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

1.5 Comments
The Java comments are the statements in a program that are not executed by the
compiler and interpreter.
Why do we use comments in a code?
• Comments are used to make the program more readable by adding the details of the
code.It makes easy to maintain the code and to find the errors easily.
• The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
Types of Java Comments
There are three types of comments in Java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the widely used
and easiest way of commenting the statements. Single line comments starts with two forward
slashes (//).
Syntax:
//This is single line comment
2) Java Multi Line Comment
The multi-line comment is used to comment multiple lines of code. It can be used to
explain a complex code snippet or to comment multiple lines of code at a time. Multi-line
comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
/*
This is
multi line
comment
*/
3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or
software application as it helps to create documentation API. These APIs are needed for
reference, i.e., which classes, methods, arguments, etc., are used in the code. The
documentation comments are placed between /** and */.
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

II. Data Types, Variables, and Operators


1.6 Introduction 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.
1.6.1 Primitive Data types
Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and boolean. The primitive types are also commonly referred to as simple types, and both
terms will be used in this book. These can be put in four groups:
• Integers: This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
• Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
• Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
• Boolean: This group includes boolean, which is a special type for representing
true/false values.
Data Type Default Value Default size
boolean FALSE 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
1. boolean: The Boolean data type is used to store only two possible values: true and false,
but the size of the boolean data type is virtual machine-dependent.
Example: Boolean a = false
2. char: 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 ch = 'A'
3. byte: It is an 8-bit signed two's complement integer. Its value-range lies between -128 to
127 (inclusive). The byte data type is used to save memory in large arrays where the memory
savings is most required.
Example: byte a = 10, byte b = -20
4. short: The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). The short data type can also be used to save memory
just like byte data type.
Example: short s = 10000, short r = -5000
5. int: 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). 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
6. long: 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). 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
7. float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its value-range
lies between 1.4e-045 to 3.4e+038. It is recommended to use a float (instead of double) if you
need to save memory in large arrays of floating point numbers.
Example: float f1 = 234.5f
8. double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its value-
range lies between 4.9e-324 to 1.8e+3.8. The double data type is generally used for decimal
values just like float.
Example: double d1 = 12.34
1.6.2 Non-primitive Types
These are the class and interface types. The name of a class or interface is the name of type.
A class object is declared as
Class_identifier object_identifier;
Similarly, an interface reference is declared as
Interface_identifier reference_identifier;
Example:
String str "Delhi":
1.6.3 Variables
Variable is name of reserved area allocated
in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
Syntax:- type identifier [ = value ][, identifier [= value ] …];
Declaring Variables
int x; // Declare x to be an integer variable;
double radius; // Declare radius to be a double variable;
char a; // Declare a to be a character variable;
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
Types of Variables
There are three types of variables in Java:
1) Local Variable: A variable declared inside the body of the method is called local variable.
A local variable cannot be defined with "static" keyword. Local variables can be accessed
directly.
2) Instance Variable: A variable declared inside the class but outside the body of the method,
is called instance variable. It is not declared as static. Instance variables cannot be accessed
directly, accessed through object.
3) Static variable: A variable which is declared as static is called static variable. It cannot be
local. Static variables can be accessed directly. You can create a single copy of static variable
and share among all the instances of the class. Memory allocation for static variable happens
only once when the class is loaded in the memory.
Example to understand the types of variables in java
class A
{
int data=50; //instance variable
static int m=100; //static variable
public static void main(String args[])
{
int n=90; //local variable
System.out.println(“Local variable n=”+n); //accessed directly
System.out.println(“Static variable m=”+m); //accessed directly
A obj=new A(); //Object Creation
System.out.println(“Instance variable m=”+obj.data); //accessed through object
}//end of class
Programming Example
public class Main
{
public static void main(String[] args)
{
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean
String myText = "Hello"; // String
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);
System.out.println(myText);
}
}
Output:
5
5.99
D
true
Hello

1.7 Static Variables and Methods


Static Variables:
• The static variables are class variables. Only one copy of such variables is kept in the
memory and all the objects share that copy.
• The static variables are accessed through class reference, whereas the instance variables
are accessed through class object reference
• The variables in a class may be modified by modifier static.
• The non-static variables declared in a class are instance variables Each object of the
class keeps a copy of the values of these variables.
Static Methods:
If you apply static keyword with any method, it is known as static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
//static varibles and Methods using direct method
class Direct
{
static int a=20;
static int b=30;
static void sum()
{
System.out.println("Sum="+(a+b));
}
public static void main(String args[])
{
System.out.println("a="+a);
System.out.println("b="+b);
sum();
}
}
Output
a=20
b=30
Sum=50

Static Block
If you need to do computation in order to initialize your static variables, you can declare
a static block that gets executed exactly once, when the class is first loaded. It is executed
before the main method at the time of classloading. Consider the following java program
demonstrating use of static blocks.
Example of static block
//static Block
class Static
{
static
{
System.out.println("Static Block");
int a=20;
int b=30;
System.out.println("Sum="+(a+b));
}
public static void main(String args[])
{
}
}
Output
Static Block
Sum=50

1.8 Attribute Final


The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
1) final variable
When a variable is declared with final keyword, its value can’t be modified, essentially,
a constant. In Java, we cannot change the value of a final variable. For example,
class Bike
{
final int speedlimit=90; //final variable
public static void main(String args[])
{
// try to change the final variable
speedlimit=400;
System.out.println("Speed limit is: "+speedlimit);
}
}//end of class
Output
Main.java:7: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
2) final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. In Java, the final method cannot be overridden by the child class.
For example,
class FinalDemo
{
// create a final method
public final void display()
{
System.out.println("This is a final method.");
}
}
class Main extends FinalDemo
{
// try to override final method
public final void display()
{
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
Main obj = new Main();
obj.display();
}
}
Output
Main.java:12: error: display() in Main cannot override display() in FinalDemo
public final void display()
^
overridden method is final
1 error

1.9 Operators
An operator performs an action on one or more operands. An operator that performs an action
on one operand is called a unary operator (+, –, ++, – –). An operator that performs an action
on two operands is called a binary operator (+, –, / , * , and more). An operator that performs
an action on three operands is called a ternary operator (? :). Java provides all the operators.
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Operator Type Category Precedence
postfix expr++ expr--
Unary
prefix ++expr --expr +expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >> >>>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
1. Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
• incrementing/decrementing a value by one
• negating an expression
• inverting the value of a Boolean
Example: ++ and –
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Output
10
12
12
10
2. Arithmetic Operator
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Example
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0
}
}
Output
15
5
50
2
0
3. Shift Operator
Right Shift Operator
The Java right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output
2
5
2
Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of
a specified number of times.
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Output
40
80
80
240

4. Relational Operator
Relational operators in Java return either true or false as a boolean type. Relation
operators are ==, !=, <,>,<=,>=.
class Main
{
public static void main(String[] args)
{
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
5. Bitwise Operator
Bitwise operators in Java are used to perform operations on individual bits. For example,
Bitwise complement Operation of 35
35 = 00100011 (In Binary)
~ 00100011
________
11011100 = 220 (In decimal)
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR
6. Logical Operator
These operators are used to perform logical “AND(&&)”, “OR(||)” and “NOT(!)”
operation, i.e. the function similar to AND gate and OR gate in digital electronics. They are
used to combine two or more conditions/constraints or to complement the evaluation of the
original condition under particular consideration.
Example
public class Test
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output
a && b = false
a || b = true
!(a && b) = true
7. Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the
value on its right to the operand on its left.
Example
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Output
14
16
8. Ternary Operator
Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot
in Java programming. it is the only conditional operator which takes three operands.
Example
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Output
2
III. Control Statements
1.10 Control Statements
Java compiler executes the java code from top to bottom. The statements are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of java code. Such statements are called control flow statements.

1.10.1 Decision Making statements


Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the condition result. There are two types of decision-making statements
in java, I.e., If statement and switch statement.
1. if statement
This is the most basic statement among all control flow statements in java. It evaluates
a Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(<condition>)
{
//block of code
}
Consider the following example in which we have used the if statement in the java code.
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output
x + y is greater than 20
2. if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, I.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
Syntax of if-else statement is given below.
if(<condition>)
{
//block of code
}
else
{
//block of code
}
Example
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
Output
x + y is greater than 20
3. else-if statement
The else-if statement contains the if-statement followed by multiple else-if statements.
In other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter any block of code. We can also define an else statement at the
end of the chain.
Example
public class Student
{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}
}
Output
Delhi
4. Nested if-statement
In nested if-statements, the if statement contains multiple if-else statements as a
separate block of code.
Example
public class Student
{
public static void main(String[] args)
{
String address = "Delhi, India";
if(address.endsWith("India"))
{
if(address.contains("Meerut"))
{
System.out.println("Your city is meerut");
}
else if(address.contains("Noida"))
{
System.out.println("Your city is noida");
}
else
{
System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in india");
}
}
}
Output
Delhi
5. Switch Statement
In Java, Switch statements are similar to if-else-if statements. The switch statement
enables us to check the variable for the range of values defined for multiple case statements.
The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
Syntax
switch <variable>
{
Case <option 1>:
//block of statements
..
..
..
Case <option n>:
//block of statements
Default:
//block of statements
}
Example
public class Student implements Cloneable
{
public static void main(String[] args)
{
int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output
2
1.10.2 Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
1. for loop:
In java, for loop is similar to C and C ++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code. The syntax to use the
for loop is given below.
for(<initialization>, <condition>, <increment/decrement>)
{
//block of statements
}
Example
public class Calculattion
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++)
{
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output
The sum of first 10 natural numbers is 55
2. for-each loop
Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The syntax to use
the for-each loop in java is given below.
for(type var : collection)
{
//statements
}
Example
public class Calculattion
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names)
{
System.out.println(name);
}
}
}
Output
Printing the content of the array names:
Java
C
C++
Python
JavaScript
3. while loop
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside
the loop statement in while loop.
The syntax of the while loop is given below.
While(<condition>)
{
//loop statements
}
Example
public class Calculattion
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10)
{
System.out.println(i);
i = i + 2;
}
}
}
Output
Printing the list of first 10 even numbers
0
2
4
6
8
10
4. do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. However, it is recommended to use the do-while loop if we don't know the
condition in advance, and we need the loop to execute at least once.
The syntax of the do-while loop is given below.
do
{
//statements
} while (<Condition>);
Example
public class Calculattion
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do
{
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output
Printing the list of first 10 even numbers
0
2
4
6
8
10
1.10.3 Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the other part of
the program. There are two types of jump statements in java, i.e., break and continue.
1. break statement
The break statement is used to break the current flow of the program and transfer the
control to the next statement outside the current flow. It is used to break the loop and switch
statement. However, it breaks only the inner loop in the case of the nested loop.
Example
public class BreakExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}
Output
0
1
2
3
4
5
6
2. continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas it skips
the specific part of the loop and jumps to the next iteration of the loop immediately.
Example
public class ContinueExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++)
{
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
System.out.println(j);
}
}
}
}
Output
0
1
2
3
5
1
2
3
5
2
3
5

You might also like