Java Unit-1 Material
Java Unit-1 Material
SYLLABUS(UNIT-1):
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or
Tokens in Java Programs, Java Statements, Command Line Arguments, User Input to
Programs, Escape Sequences, Comments, Programming Style.
Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of
Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants,
Symbolic Constants, Formatted Output with printf() Method, Static Variables and Methods,
Attribute Final, Introduction to Operators, Precedence and Associativity of Operators,
Assignment Operator ( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -)
Operators, Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise
Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions,
Ternary Operator?:, Switch Statement, Iteration Statements, while Expression, do–while
Loop, for Loop, Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.
1. History of JAVA:
The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital devices such
as set-top boxes, televisions etc. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. There are given the major points that describes the history of java.
i) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
ii) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
iii) After that, it was called Oak and was developed as a part of the Green project.
Why Oak name for java language?
iv) Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc. During 1991 to 1995 many people around the world
contributed to the growth of the Oak, by adding the new features. Bill Joy, Arthur van
Hoff,Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the
Original prototype.
v) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
technologies.
Why they chose java name for java language?
vi) The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" etc. According to James Gosling "Java was one of the
top choices along with Silk". Since java was so unique, most of the team members preferred
java.
vii) Java is an island of Indonesia where first coffee was produced (called java coffee).
viii) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
ix) In 1995, Time magazine called Java one of the Ten Best Products of 1995 and JDK 1.0
released in(January 23, 1996).
The key that allows Java to solve both the security and
the portability problems is the byte code. The output of Java
Compiler is not directly executable file. Rather, it contains
highly optimized set of instructions. This set of instructions is
called, "byte code". This byte code is designed to be executed
by Java Virtual Machine (JVM). The JVM also called as the
interpreter for byte code. JVM also helps to solve many
problems associated with web-based programs.
Translating a Java program into byte code makes it much
easier to run a program in a wide variety of environments
because only the JVM needs to be implemented for each
platform. Figure: Java Virtual Machine (JVM)
Once the run-time package exists for a given system, any Java program can run on it.
Remember, although the details of the JVM will differ from platform to platform, all
understand the same Java byte code. Thus, the execution of byte code by the JVM is the
easiest way to create truly portable programs.
The fact that a Java program is executed by the JVM also helps to make it secure.
Because the JVM is in control, it can contain the program and prevent it from generating side
effects outside of the system.
S
N C C++ JAVA
o
3 The code is executed directly. The code is executed The code is executed by the JVM.
directly.
5 It uses a compiler only to It also uses a compiler Java uses both compiler and interpreter and
translate the code into only to translate the it is also known as an interpreted language.
machine language. code into machine
language.
6 It generates the .exe, and .bak, It generates .exe file. It generates .class file.
files.
7 The source file has a .c The source file has a The source file has a .java extension.
extension. .cpp extension.
8 It supports pointers. It also supports Java does not support the pointers concept
pointers. because of security.
9 It supports union and structure It also supports union It does not support union and structure data
data types. and structure data types. types.
10 It uses pre-processor It uses pre-processor It does not use directives but uses packages.
directives such as #include, directives such as
#define, etc. #include,#define,
#header, etc.
12 It does not support exception It supports exception It also supports exception handling.
handling. handling.
13 It uses the calloc(), malloc(), It uses new and delete It uses a garbage collector to manage the
free(), and realloc() methods operator to manage the memory.
to manage the memory. memory.
5. Object-Oriented Programming(OOP) Principles
All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are as follows:
i. Abstraction
ii. Encapsulation
iii. Inheritance
iv. Polymorphism
Compile-time polymorphism
Runtime polymorphism
i) Abstraction
Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or non-essential units are not displayed to the user.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object, ignoring the irrelevant details. The properties and behaviors of
an object differentiate it from other objects of similar type and also help in
classifying/grouping the object. In Java, abstraction is achieved by interfaces and abstract
classes. We can achieve 100% abstraction using interfaces.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will stop the car, but
he does not know how on pressing the accelerator, the speed is actually increasing. He does
not know about the inner mechanism of the car or the implementation of the accelerators,
brakes etc. in the car.
ii) Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse. One way to think about
encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily
accessed by other code defined outside the wrapper. Access to the code and data inside the
wrapper is tightly controlled through a well-defined interface.
Technically, in encapsulation, the variables or the data in a class is hidden from any
other class and can be accessed only through any member function of the class in which
they are declared. In encapsulation, the data in a class is hidden from other classes, which is
similar to what data-hiding does. So, the terms “encapsulation” and “data-hiding” are used
interchangeably.
iii) Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features of another class.
Superclass: The class whose features are inherited is known as superclass (also known
as base or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as
derived or extended or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
iv) Polymorphism
It refers to the ability of object-oriented programming languages to differentiate
between entities with the same name efficiently. This is done by Java with the help of the
signature and declaration of these entities. Polymorphism in Java is mainly of two types:
Compile-time polymorphism
Method overloading is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding in Java. Method Overloading allows different methods to
have the same name, but different signatures where the signature can differ by the number
of input parameters or type of input parameters, or a mixture of both.
Runtime polymorphism
Method overriding is also known as Run Time Polymorphism or Dynamic
Polymorphism or Late binding in Java. Overriding is a feature that allows a subclass or
child class to provide a specific implementation of a method that is already provided by one
of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature, and same return type(or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in the super-class.
i. Identifiers
Identifiers are used for class names, method names, and variable names. An
identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or
the underscore and dollar-sign characters. They must not begin with a number, lest they be
confused with a numeric literal. In Java, identifiers are also called variables since they
identify the memory locations. Java is case-sensitive, so VALUE is a different identifier than
Value.
Rules for Naming Identifier:
The first character of an identifier must be a letter, or dollar($) sign.
The subsequent characters can be letters, an underscore, dollar sign or digit.
White spaces are not allowed within identifiers.
Identifiers are case sensitive so VALUE is a different identifier than Value
Some examples of valid identifiers are:
Average Height A1 Area_Circle
Invalid Identifiers are as follow:
2types Area-circle Not/ok
iii. Literals
A literal is a value that can be passed to a variable or constant in a program. Literals can
be numeric, boolean, character, string notation or null. A constant value in Java is created by
using a literal representation of it. It can be assigned directly to a variable. Java has various
types of literals. There are the majorly six types of literals in Java as follows:
1. Integer Literal
2. Floating point Literals
3. Boolean Literal
4. Character Literal
5. String Literal
6. Null Literal
1. Integer Literal
Integer literals are sequences of digits. There are three types of integer literals:
• Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It
may have a positive (+) or negative (-) . For example, int decVal = 9 ;
• Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.
For example, int octVal = 065;
• Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as
hexadecimal integers. It may also include a character from a to f or A to F that
represents numbers from 10 to 15, respectively. For example, int hexVal = Ox6AF32
• Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 . Prefix 0b
represents the Binary system. You can create binary literals in Java SE 7 and later.
int binVal = 0b1001;
2. Floating point Literals
• The vales that contain decimal are floating literals. In Java, float and double primitive
types fall into floating-point literals.
• For Floating-point data types, we can specify literals in only decimal form, and we
cant specify in octal and Hexadecimal forms. Floating-point literals for float type end
with F or f. Example: float length = 15.42f;
3. Boolean Literal
• Boolean literals are the value that is either true or false. It may also have values 0 and
1. For example, boolean x=true; boolean y=false;
4. Character Literal
• A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, char ch=’A’;
char ch=’9’;.
5. String Literal
• String literal is a sequence of characters that is enclosed between double quotes ("")
marks. It may be alphabet, numbers, special characters, blank space, etc. For example,
String str1=”java is a Object Oriented Programming”;
6. Null Literal
• Null literal is often used in programs as a marker to indicate that reference type object
is unavailable. The value null may be assigned to any variable, except variables of
primitive types.
• Example, String Name = null; [Link](Name); //it will not give any output
iv) Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon and it is used to terminate statements. The separators are
shown in the following table:
v) Operators
Operators are used to perform operations on variables and values. Java provides
many types of operators which can be used according to the need. They are classified
based on the functionality they provide. Some of the types are: Unary Operators ,
Arithmetic Operators,Assignment Operators ,Logical Operators ,Shift Operators ,Bitwise Ope
rators ,Ternary Operators and Relational Operators.
Declaration Statement
In declaration statements, we declare variables and constants by specifying their data
type and name. A variable holds a value that is going to use in the Java program.
For example: int quantity;
String name;
Expression Statement
Expression is an essential building block of any Java program. Generally, it is used to
generate a new value. Sometimes, we can also assign a value to a variable. In Java,
expression is the combination of values, variables, operators, and method calls.
For example: num =2; sum = a + b;
Control Statement
Control statements decide the flow of sequence of execution of statements in a
program. They include selection, iteration and jump statements.
For example:
int number;
number=20;
if (number > 10 )
{
[Link](number + " is greater than 10");
}
Synchronized Statement
There are used in multi-threading. Synchronized block can be used to perform
synchronization on any specific resource of the method.
Example: synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
Guarding statement
Guarding statements are used for safe handling of code that may cause exceptions .
These statements use the keywords. Example: try, catch, throw, throws and finally.
i. Integers
• The integer group contains byte, short, int, long. These data types will need different
sizes of the memory. These are assigned positive and negative values. The width and
ranges of these values are as follow:
byte:
• The smallest integer type is byte. This is a signed 8-bit type that has a range from –
128 to [Link] of type byte are especially useful when you’re working with a
stream of data from a network or file.
• For example, byte b, c; // where b and c are identifiers
short:
• short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the
least-used Java type. Examples of short variable declarations: short s; short t;
int:
• The most commonly used integer type is int. It is a signed 32-bit type that has a range
from –2,147,483,648 to 2,147,483,647. Example: int x=12;
long:
• long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. The range of a long is quite large.
• Example: long x=123456;
float:
• The float type represents single precision and double represents double precision. For
single precision, 32 bits are used to represents the floating point number. For double
precision, 64 bits are used to represents the floating point number.
• A float can have a 7-digit decimal precision and ends with an ‘f’ or ‘F’
Example for Floating-Point Data Type(float):
class FloatDataTypes
{
public static void main(String args[]) {
float f = 65.20298f;
[Link]("The float variable is: " + f);
}
}
double:
• Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors.
Example program to calculate the area of a circle
import [Link].*;
class Circle
{
public static void main(String args[])
{
double r, area, pi;
r=12.3; // radius of circle
pi=3.14;
area=pi * r * r; // compute area
[Link]("The Area of the Circle is:"+area);
}
}
Output: The Area of the Circle is:475.0506000000001
iii. Characters
• In Java, the data type used to store characters is char. Java char is a 16-bit type. The
range of a char is 0 to 65,536. There are no negative chars.
• The char data type stores a single character. It stores both lower case and upper case
characters which must be enclosed in single quotes. The char data type in Java
supports Unicode characters .
Example: // Demonstrate char data type.
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
} Output: ch1 and ch2: X Y
iv. Booleans
• Java has a primitive type, called boolean, for logical values. It can have only one of
two possible values , true or false. Boolean data type represents only one bit of
information either true or false.
Example: // Demonstrate boolean values
class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
if(b) [Link]("This is executed."); //a boolean value can control the if statement
b = false;
if(b) [Link]("This is not executed.");
// outcome of a relational operator is a boolean value
[Link]("10 > 9 is " + (10 > 9));
}
}
Output: b is false
b is true
This is executed.
10 > 9 is true
iv. Interface
An interface is declared like a class. Interface is an abstract way of defining the structure of a
class. Java permits multiple inheritance through interfaces. An interface can have methods
and variables, but the methods declared in an interface are by default abstract .
Syntax: interface interfacename{
final type varname1= value;
…………….
final type varnameN= value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
…………………………..
return-type method-nameN(parameter-list);
}
Example :
int a, b, c; // declares three integers, a, b, and c.
int d = 3, e, f = 5; // declares three more integerss, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; //the variable x ahs the value 'x‘
Dynamic Initialization of the variable
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared. We can also assign a value to the variable dynamically.
Example: Demonstrate dynamic initialization
class DynInit {
public static void main(String []args) {
double a=2.0 , b=3.0;
double c=a+b; // c is dynamically initialized
[Link](“c value is:”+ “ “+c);
}
}
Types of variables: In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
• Local Variables are a variable that are declared inside the body of a method.
2. Instance Variables
• Instance variables are defined outside a method declaration. They are object specific
and are known as instance variables.
3. Static Variables
• We use the static keyword before the variable to define a variable, and this variable is
called as static variable.
• Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables.
• When a method is completed, all of its variables are normally deleted. Sometimes we
need to store a variable even after completion of method execution.
Example for declaring types of variables
class VarTypes
{
static int a = 1; //static variable
int b = 2; //instance variable
void method1()
{
int c = 3; //local variable
}}
The Scope and Lifetime of Variables:
Scope of a variable is the part of the program where the variable is accessible. Java
allows, to declare a variable within any block. A block begins with opening curly brace and
ended with end curly brace. Thus, each time we start new block, we create new scope. A
scope determines what objects are visible to parts of your program. It also determines the life
time of the objects. Many programming languages define two scopes: Local and Global. As
a general rule a variable defined within one scope, is not visible to code defined outside of the
scope. Scopes can be also nested. The variable defined in outer scope are visible to the inner
scopes, but reverse is not possible.
Example for Scope and Lifetime of Variables
public class ScopeDemo
{
public static void main(String args[]) {
void method1()
{ //outer block
int a;
int a=10;
if(a==10) // here a , b, c are visible to the inner scope
{ // inner block
int b=a*20;
int c=a+30;
} //end of inner block
b=20*2; // b is not known here, which is declared in inner scope
[Link]("a is " + a); // a is still known here.
} //end of the outer block
}}
16. Symbolic Constants
• Constants may appear repeatedly in number of places in the program. Symbolic
constants are nothing more than a label or name that is used to represent a fixed value
that never changes throughout a program. They can’t be declared inside a method.
They should be used only as class data members in the beginning of the class.
Syntax : final type symbolicname = value;
Example: final float PI =3.14159; // declaring PI and STRENGTH constants
final int STRENGTH =80;
• After declaration of symbolic constants they shouldn’t be assigned any other
value with in the program by using an assignment statement.
For example, STRENTH = 100 is illegal
17. Formatted Output with printf() Method
• Java printf() is a method that belongs to the [Link] class and it is very
similar to the printf() function in C. It is used to format the output and print it to the
console..
• The printf() method of Java PrintStream class is a convenience method to write a
String which is formatted to this output Stream. It uses the specified format string and
arguments. The [Link]() function in Java allows users to print formatted
data. The general syntax of this method is as follows:
[Link](string)
[Link](format string, variables or objects separated by comma)
Example: // Java program to demonstrate working of printf() method
import [Link];
public class FormatterPrintfExample {
public static void main(String args[])
{
int x = 500;
[Link]("Printing integer value: x = %d\n",x);
// this will print it upto 2 decimal places
[Link]("Formatted with precision:PI = %.2f \n",[Link]);
float n = 5.2f; // automatically adds zero to the rightmost part of decimal
[Link]("Formatted to specific width: n = %.4f\n", n);
String str = "Department of CSE";
[Link]("%s", str);
}}
Output:
18. Static Variables and Methods
• The static keyword is used to construct methods that will exist regardless of
whether or not any instances of the class are generated. Any method that uses the
static keyword is referred to as a static method.
• A static method in Java is a method that is part of a class rather than an instance of
that class. Static methods have access to static variables without using the class’s
object (instance). It doesn’t require an object of the class.
• In both static and non-static methods, static methods can be accessed directly.
• Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables.
• When a method is completed, all of its variables are normally deleted. Sometimes we
need to store a variable even after completion of method execution.
• Syntax for declare the static variable, static type variable = value;
• Syntax for declare the static method:
Access_modifier static void methodName() {
// Method body }
• The static variable and method is only accessible by class name. Syntax:
[Link];
[Link]();
Example for static variables and methods program:
public class StaticExample {
static int num = 500; //static variable
static String str = “II CSE SACET";
static void display() // This is Static method
{
[Link]("\nStatic number is " + num);
[Link]("\nStatic string is " + str);
}
void nonstatic() // non-static method
{
display(); // Static method can also access in non static method
}
public static void main(String args[]) // main method
{
StaticExample obj = new StaticExample(); //object creation
[Link](); // This is object to call non static function
[Link](); // static method can called directly without an obj
}
}
1. Final Variables
When a variable is declared with the final keyword, its value can’t be modified,
essentially, a constant. If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable,
but It can't be changed because final variable once assigned a value can never be changed.
class BikeRace{
final int speedlimit=90; //final variable
void run(){
speedlimit=100; // final variable value can’t be change
}
public static void main(String args[]){
BikeRace obj=new BikeRace();
[Link]();
}
} Output: Compile time Error
2. final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. We must declare methods with the final keyword for which
we are required to follow the same implementation throughout all the derived classes.
Example for final method:
class A { //A is super class
final void meth() { // final method
[Link]("This is a final method.");
}
}
class B extends A { //B is sub class
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}}
• Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
so, a compile-time error will result.
3. final class
When a class is declared with final keyword, it is called a final class. A final
class cannot be extended(inherited). Declaring a class as final implicitly declares all of its
methods as final, too.
For example,
final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
• As the comments imply, it is illegal for B to inherit A since A is declared as final.
There are two types of conversion. They are Implicit Conversion, and Explicit Conversion.
Implicit Conversion or Java’s Automatic Conversions:
In the case of the implicit conversion type conversion is automatically performed by
java when the types are compatible. For example, the int can be assigned to long. The byte
cane assigned to short. However, all the types are compatible, thus all the type conversions
are implicitly allowed. For example, double is not compatible with byte.
Conditions for automatic conversion
1. The two types must be compatible
2. The destination type must be larger than the source type
When automatic type conversion takes place the widening conversion takes place. For
Example,
int a; //needs 32 bits
byte b=45; //needs the 8 bits
a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b; int i = 257;
double d = 323.142;
[Link]("\nConversion of int to byte.");
b = (byte) i;
[Link]("i and b " + i + " " + b);
[Link]("\nConversion of double to int.");
i = (int) d;
[Link]("d and i " + d + " " + i);
[Link]("\nConversion of double to byte.");
b = (byte) d;
[Link]("d and b " + d + " " + b); } }
i) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. They
act as basic mathematical operations. Java has the typical collection of numeric operators: the
binary operators + for addition, - for subtraction, * for multiplication, / for division, and % for
modulus. The operands of the arithmetic operations are of numeric type. The table below lists
the arithmetic operators in Java.
Operator Name Description Example Result
Example,
public class TernaryOperatorExample
{
public static void main(String args[])
{
int a, b, max;
a = 20;
b = 15;
max = (a>b) ? a: b;
[Link]("Max value is: " + max);
}
}
The condition (a>b) is evaluated first. If the condition is true then a value will be
return to the Max. otherwise b value will be return.
These operators are again classified into two categories: Bitwise Logical operators, and
Shift operators.
The Bitwise Logical Operators:
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation. The bitwise operators are applied to each individual bit within each operand.
00001010 10
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then
the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
00101111 47
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.
Otherwise, the result is zero. The following example shows the effect of the ^.
00101010 (42)
^ 00001111 (15)
00100101 (37)
// Demonstrate the bitwise logical operators.
class BitLogic
{
public static void main(String args[])
{
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
[Link](" a|b = " +c);
[Link](" a&b = " +d);
[Link](" a^b = " +e);
[Link]("~a&b|a&~b = " +f);
[Link](" ~a = " + g);
}
}
Output:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Bitwise Shift Operators: (left shift and right shift):
The Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of
times. It has this general form: value << num
Here, num specifies the number of positions to left-shift the value in value. That is, the
<<moves all of the bits in the specified value to the left by the number of bit positions
specified by num.
The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number
oftimes. Its general form is shown here: value >> num
Here, num specifies the number of positions to left-shift the value in value. That is, the
>>moves all of the bits in the specified value to the right by the number of bit positions
specified by num.
Note: The operators =,?:, ++, and – are having Right to Left Associativity. The remaining
Operators are having Left to Right Associativity.
Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often
necessary to obtain the result you desire. For example, consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this
expression
can be rewritten using redundant parentheses like this: a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result,
you will need to parenthesize the expression like this:(a >> b) + 3
23. Control Statements
The control statements are used to control the flow of execution of statements in a
program. The control statements in Java are categorized into 3 categories:
1. Conditional/Selection Statements/Decision Making Statements
2. Iteration Statements/Loops/Repetative
3. Jump Statements or Unconditional Statements
Example,
import [Link].*;
public class SwitchExample {
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Enter day value");
int day = [Link]();
String strday;
switch (day)
{ // Switch statement with int data type
case 1: strday = "Monday";
break;
case 2: strday = "Tuesday";
break;
case 3: strday = "Wednesday";
break;
case 4: strday = "Thursday";
break;
case 5: strday = "Friday";
break;
case 6: strday = "Saturday";
break;
case 7: strday = "Sunday";
break;
default: strday = "Invalid day"; // Default case
}
[Link](strday);
}}
Nested-Switch Statement:
Nested-Switch statements refers to Switch statements inside of another Switch Statements.
You can use a switch as part of the statement sequence of an outer switch. This is called a
nested switch.
Syntax:
switch(expression1) //outer switch
{
case 1: switch(expression2) // inner switch or // Nested switch
{
case 4: //statement sequence
break;
case 5: //statement sequence
break;
default: //code to be executed if expression2 doesn't
match with any cases
} //end of inner switch
break;
case 2: //statement sequence
break;
default: //code to be executed if expression2 doesn‘t match with any cases
} //end of outer switch
Example, output:
import [Link];
public class NestedSwitchExample {
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
[Link]("Enter Branch Code");
int BranchCode = [Link]();
char branch = 'C'; //C - CSE, E - ECE, A - AI&ML
switch( BranchCode ) //outer switch
{
case 1: switch( branch ) //inner switch 1
{
case 'C‘: [Link](" Java Programig, Web Technologies");
break;
case 'E‘:[Link]("Micro processors, Embedded Systems");
break;
case 'A‘: [Link]("Machine Learning, Artficial Intelligence");
break;
} //end of inner switch 1
break;
case 2: switch( branch ) //inner switch2
{
case 'C‘: [Link]("Computer Organization, Mean Stack Technologies");
break;
case 'E': [Link]("VLSI, Microelectronics");
break;
case 'A': [Link]("DBMS, CYBER SECURITY");
break;
} //end of inner switch 2
break;
default: [Link]("Invalid Branch");
} } } //end of outer switch
2. Loops (Iteration Statements):
The loop control statements are used to execute a group of statements repetitively.
Java provides three ways for executing the loops. There are three types of loops in Java.
i. while loop
ii. do-while loop
iii. for loop
i. while loop
The while loop executes a block of code repeatedly until the condition is FALSE.
Once the condition gets FALSE, it exits from the body of loop. The while loop is called
an Entry control loop because the condition is checked before entering the loop body. This
means that first the condition is checked. If the condition is true, then block of code will be
executed. The general form of the while statement is as follows:
while(condition)
{
// body of loop
increment or decrement statement
}
• The condition can be any Boolean expression. The body of the loop will be executed
as long as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop. The curly braces are
unnecessary if only a single statement is being repeated.
For example, Write a Java program to check whether given number is Prime number
or not using while loop.
//A prime number is a positive integer and that is divisible only by itself and 1
import [Link].*;
public class PrimeNumCheck
{
public static void main(String args[])
{
int i=1, num, k=0;
Scanner in = new Scanner([Link]);
[Link]("Enter the Number:"); output:
num =[Link]();
while(i<=num)
{
if(num%i==0)
k++;
i++;
}
if(k==2)
[Link](num+"is a prime number");
else
[Link](num+"is not a prime number");
}
}
• continue may specify a label to describe which enclosing loop to continue. Here is an
example program that uses continue to print a triangular multiplication table for 0
through 5. Syntax : label: statement(s);
continue label;
Example, // Using continue with a label.
public class ContinueLabel { output:
public static void main(String args[]) {
outer: for (int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if(j > i)
{
[Link]();
continue outer;
}
[Link](“ " + (i * j));
}
}
} }
3. return statement
The return statement is used to explicitly return from a method. At any time in a
method, the return statement can be used to cause execution to branch back to the caller of
the method. Thus, the return statement immediately terminates the method in which it is
executed.
Syntax: return returnvalue;
Example for return statement:
class ReturnExample {
int compareNum(int x,int y)
{
if(x>y)
return x;
else
return y;
}}
public class ReturnDemo {
public static void main(String ar[]) {
ReturnExample obj = new ReturnExample();
int result = [Link](5,6);
[Link]("The biggest number among x and y is: " + result);
} }
ST. ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
FAQs
Subject : JAVA PROGRAMMING Year/Sem: II [Link] – II Sem
Academic Year: 2022-23 Regulation: R20
UNIT-1:
1. a) List and explain Java buzzwords. Which factors are making Java famous
Language?
b) What are the components of JAVA platform? Explain
2. a) What is the role and responsibility of JVM in program execution? With a neat
diagram, explain the Java Virtual Machine architecture.
b) Justify the validity of the statement “Byte code of Java gives high performance”.
3. a) Explain in detail the most significant features of JAVA programming.
b) Is Java a secure and robust language? Justify your answer.
c) Why Java is architectural neutral language?
d) How JAVA is a platform independent language?
4. a) Write a java program to illustrate the increment & decrement operators, shift
operators and ternary operator.
b) Demonstrate precedence rules and associativity with an example Java program.
5. a) Why ‘main()’ method is declared as public static in JAVA programming?
b) How to perform type casting in java? Differentiate it from primitive type
conversion with an example program.
6. a) What are the different primitive data types in java? Give their sizes in bits. How
they are different from reference data types?
b) How to use break and continue statements in java?
7. a)Write a java program to illustrate the usage of conditional statements and looping
statements.
b) Write a java program that inputs an integer, ‘n’ from the command line and
displays the string “1+2+3+…+n=sum” and also compute the sum.
8. a) Write the importance of command line arguments. Write a Java program which
accepts the input from keyboard to display Fibonacci series.
b) Write the purpose of static keyword in Java.
c) List out the characteristics of the static method.
9. a) Discuss the differences between Procedural Programming Language and
Object Oriented Programming language.
b) What is meant by byte code? Explain how Java is platform independent
10 a) Discuss any three OOP Principles with an example.
b) Describe the structure of a typical Java program with an example
11 a) List and explain the Tokens in the Java language.
b) Demonstrate Bitwise operators using a Java program.
12 a) List and explain the control statements with examples.
b) Demonstrate the operator precedence using a Java program
13 a) Explain various Key Words available in Java.
b) Discuss the rules in Automatic Type Promotion in Expressions.
14.a) Explain various Operators in Java.
b) Write a Java Program to test whether a given character is Vowel or Consonant.