0% found this document useful (0 votes)
13 views

UNIT-II-JAVA

The document provides an overview of Java programming concepts, focusing on programming constructs, data types, and operators. It details variables, primitive and non-primitive data types, naming conventions, keywords, literals, and various types of operators. The content serves as an introductory guide for understanding the foundational elements of Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

UNIT-II-JAVA

The document provides an overview of Java programming concepts, focusing on programming constructs, data types, and operators. It details variables, primitive and non-primitive data types, naming conventions, keywords, literals, and various types of operators. The content serves as an introductory guide for understanding the foundational elements of Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

JAVA PROGRAMMING UNIT I

Programming Constructs: Variables, Primitive Data types, Identifiers-


naming Conventions, Keywords, literals, Operators – Binary, Unary and
Ternary, Expressions, Precedence rules and associativity, primitive type
conversion and casting, flow of control-branching, conditional, loops.,
Classes and Objects: Classes , Objects, Creating Objects, Methods,
Constructors-Constructors Overloading, Clean-up unused objects –
Garbage Collector, Class Variables and Methods – Static Method, this
Keyword, Arrays, Command Line Arguments.

Variables: The variable is the basic unit of storage in a Java program. A


variable is defined by the combination of a type, an identifier, and an optional
initializer.
Syntax: Type identifier = value;
Ex: int sum = 0;

Data Types: Every variable in java has a data type. Data types specify the size
and type of value that can be stored in a variable. Java language is rich in its
data types and there are two types of data types. They are
1. Primitive data types
2. Non-primitive data types
The classification of data types in java are shown in figure below.

Figure: Data Types in Java


Primitive Data Types:- The primitive data types are also commonly referred
to as simple data types. Primitive data types are classified into two types. They
are
1. Numeric data types
2. Non-numeric data types

Narasaraopeta Engineering College :: Narasaraopet Page No. : 1


JAVA PROGRAMMING UNIT I

Numeric data types: In Java, six of the eight primitive data types are numeric
types. Numeric data types are classified into two types. They are
1. Integer data types
2. Floating point data types
Integer data types: Integer data types are used to store whole numbers that
have no fractional part. Integer data types are classified into four types. They
are
1. byte
2. short
3. int
4. long
byte: byte data type is an 8-bit signed integer number. The negative numbers
are expressed in two‘s complement form. The range accepted by byte is -128
to127 i.e. -27 to 27-1. Default value stored in byte variable is 0. byte data type is
used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an integer.
Ex: byte a = 100, byte b = -50
short: short data type is a 16-bit signed integer number. The negative
numbers are expressed in two‘s complement form. The range accepted by
byte is -32,768 to 32,767 i.e. -215 to 215-1. Default value stored in short
variable is 0.
Ex: short s = 10000, short r = -20000
int: int data type is a 32-bit signed integer number. The negative numbers are
expressed in two‘s complement form. The range accepted by int is -
2,147,483,648 to 2,147,483,647 i.e. -231 to 231 -1. int is generally used as the
default data type for integer values unless there is a concern about memory.
Default value stored in int variable is 0.
Ex: int a = 100000, int b = -200000
Long: Long data type is a 64-bit signed integer number. The negative numbers
are expressed in two‘s complement form. The range accepted by long is
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 i.e. -263 to 263 -1. This
type is used when a wider range than int is needed. Default value stored in
long variable is 0.
Ex: long a = 100000L, long b = -200000L
Floating point data types: Floating point data types are used to store numbers
that have a fractional part. Floating point data types are classified into two
types. They are

Narasaraopeta Engineering College :: Narasaraopet Page No. : 2


JAVA PROGRAMMING UNIT I

1. float
2. double
float: float data type is a single-precision 32-bit floating point number. float is
mainly used to save memory in large arrays of floating point numbers. Default
value stored in float variable is 0.0
Ex: float f1 = 234.5f
double: double data type is a double-precision 64-bit floating point number.
This data type is generally used as the default data type for fractional numbers.
Default value stored in double variable is 0.0
Ex: double d1 = 123.4
Non-Numeric data types: In Java, two of the eight primitive data types are
non-numeric types. Non-Numeric data types are classified into two types. They
are
1. char data types
2. boolean data types
char: char data type is a single 16-bit Unicode character. The range accepted
by char is 0 to 65,535 i.e. 0 to 216 -1. Char data type is used to store any
character.
Ex: char letterA = 'A'
boolean: boolean data type represents one bit of information. There are only
two possible values i.e. true and false. This data type is used for simple flags
that track true/false conditions. Default value is false
Ex: boolean found = true
Non-Primitive Data Types:- The non-primitive data types are also commonly
referred as derived data types. Non-Primitive data types are classified into
three types. They are
1. Classes
2. Arrays
3. Interfaces
Classes: Class is an encapsulation of data along with its method. It is a user
defined data type. It acts as an template for creating objects.
Arrays: An array is a group of similar data items referred to by a common
name.
Interfaces: Interfaces are syntactically similar to classes, but they lack in
instance variables, and their methods are declared without any body.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 3


JAVA PROGRAMMING UNIT I

Identifiers-naming Conventions: Identifiers are used for class names, method


names, and variable names.
 Class names should be nouns with the first letter of each internal word
capitalized. Keep the class names simple and descriptive.
Ex: class MaxThree
 Interface names should be capitalized like class names.
Ex: interface FigureArea
 Methods should be verbs with the first letter lowercase and the first
letter of each internal word capitalized.
Ex: area()
 Variables follow conventions similar to that of method names. However,
when we use an identifier in a class, we can easily say if it is a method
name or a variable name because of the parentheses that are placed
adjacent to method name. The rules for variable names in Java are
1. Variable names are case-sensitive.
2. A variable‘s name can be any legal identifier.
3. It can contain Unicode letter, Digits and Two Special
Characters such as Underscore and dollar Sign.
4. Length of Variable name can be any number.
5. Its necessary to use Alphabet at the start (however we can use
underscore , but do not use it )
6. Some auto generated variables may contain ‗$‗ sign. But try to
avoid using Dollar Sign.
7. White space is not permitted.
8. Special Characters are not allowed.
9. Digit at start is not allowed.
10. Subsequent characters may be letters, digits, dollar signs, or
underscore characters.
11. Variable name must not be a keyword or reserved word.
 Constants i.e. variables declared as final should use all uppercase letters
with words separated by underscores ("_").
Ex: static final int MAX_WIDTH = 999;
 Package name is always written in all-lowercase. In a multileveled
package the package name is separated with sub package name by
using a period(.).
Ex: package p1;
pakage p1.p2.p3;

Narasaraopeta Engineering College :: Narasaraopet Page No. : 4


JAVA PROGRAMMING UNIT I

Keywords: Keywords are the reserved words of the language. They have to be
used for the specified purpose only. There are 50 keywords currently defined in
the Java language as given in the table below. These keywords cannot be used
as names for a variable, class, or method.

Literals: Literal is a constant value in Java. Literal can be any number, text, or
other information that represents a value. Depending on the value the literals
are classified into 4 types. They are
1. Integer Literal
2. Floating-Point Literals
3. Character Literals
4. String Literals
Integer Literals: Any whole number is an integer literal. Examples are 1, 2, 3,
and 42. These are all decimal values, meaning they are describing a base 10
number. There are two other bases which can be used in integer literals, octal
(base eight) and hexadecimal (base 16). Octal values are denoted in Java by a
leading zero. Normal decimal numbers cannot have a leading zero. Thus, the
valid value 09 will produce an error from the compiler, since 9 is outside of
octal‘s 0 to 7 range. A more common base for numbers used by programmers
is hexadecimal. A hexadecimal constant with a leading zero-x, (0x or 0X). The
range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
Floating-Point Literals: Floating-point numbers represent decimal values with a
fractional component. They can be expressed in either standard or scientific

Narasaraopeta Engineering College :: Narasaraopet Page No. : 5


JAVA PROGRAMMING UNIT I

notation. Standard notation consists of a whole number component followed


by a decimal point followed by a fractional component. For example, 2.0,
3.14159, and 0.6667 represent valid standard-notation floating-point numbers.
Scientific notation uses a standard-notation, floating-point number plus a
suffix that specifies a power of 10 by which the number is to be multiplied. The
exponent is indicated by an E or e followed by a decimal number, which can be
positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100.
Floating-point literals in Java default to double precision. To specify a float
literal, an F or f must be append to the constant.
Boolean Literals: Boolean literals are simple. There are only two logical values
that a boolean value can have, true and false. The values of true and false do
not convert into any numerical representation. The true literal in Java does not
equal 1, nor does the false literal equal 0. In Java, they can only be assigned to
variables declared as boolean, or used in expressions with Boolean operators.
Character Literals: Characters in Java use the Unicode character set. They are
16-bit values that can be converted into integers and manipulated with the
integer operators, such as the addition and subtraction operators. A literal
character is represented inside a pair of single quotes. Ex: ‗a‘, ‗z‘, and ‗@‘.
String Literals: String literals in Java are a sequence of characters enclosed
between a pair of double quotes. Ex: ―Hello World‖.

Operators: An operator is a symbol that tells the computer to perform certain


mathematical operations.
Classification of operators based on number of operands: Depending on
number of operands passed to the operator, the operators can be classified
into three categories. They are
1. Unary Operator
2. Binary Operator
3. Ternary Operator
Unary Operator: When one operand is passed to the operator then such an
operator is called Unary operator.
Ex:- unary minus(-), incrementing(++), decrementing(--) etc.
Binary Operator: When two operands are passed to the operator then such an
operator is called Binary operator.
Ex:- addition(+), lessthan(<), Bitwise And(&) etc.
Ternary Operator: When three operands are passed to the operator then such
an operator is called ternary operator.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 6


JAVA PROGRAMMING UNIT I

Ex:- Conditional Operator ( ? : )


Classification of operators based on operation: Depending on the operation
performed by the operator, the operators can be classified into seven
categories. They are
1. Arithmetic Operators
2. Bitwise Operators
3. Relational Operators
4. Boolean Logical Operators
5. Short Circuit Logical Operators
6. Assignment Operators
7. Conditional Operator
Arithmetic Operators: Arithmetic operators are the operators which take
numerical values as the input and produces numerical values as the output.
The following table lists the arithmetic operators:
Operator Purpose Example Result
+ Addition 12 + 4.9 16.9
– Subtraction(unary minus) 12 - 4.9 7.1
* Multiplication 12 * 4.9 58.8
/ Division 12 / 4.9 2.45
% Modulus 12 % 4.9 2.2
++ Increment Take a=10; a++ 11
+= Addition assignment Take a=10; a+=10 20
–= Subtraction assignment Take a=10; a-=10 0
*= Multiplication assignment Take a=10; a*=10 100
/= Division assignment Take a=10; a/=10 1
%= Modulus assignment Take a=10; a%=10 0
The modulus operator, %, returns the remainder of a division
operation. It can be applied to floating-point types as well as integer types.
The increment operator increases its operand by one. The decrement
operator decreases its operand by one. These operators are unique, since
they can be used in prefix and postfix. In prefix notation the
increment/decrement operator precede the operand. In the prefix form, the
operand is incremented or decremented before the value is obtained for use
in the expression. In postfix notation the increment/decrement operator
follow the operand. In postfix form, the previous value is obtained for use in
the expression, and then the operand is modified.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 7


JAVA PROGRAMMING UNIT I

Bitwise Operators: Java's bitwise operators operate on individual bits of integer


(int and long) values. If an operand is shorter than an int, it is promoted to int
before doing the operations.
Asuume a = 0011 and b = 0110

Operator Purpose Example Result


~ Bitwise unary NOT ~0011 1100
& Bitwise AND 0011 & 0110 0010
| Bitwise OR 0011 | 0110 0111
^ Bitwise exclusive OR 0011 ^ 0110 0101
>> Shift right 0011 >> 1 0001
>>> Shift right zero fill 1111>>2 (-1 in 4 bits) 0011
<< Shift left 0011 << 1 0110
&= Bitwise AND assignment a &= b 0010
|= Bitwise OR assignment a |= b 0111
>>= Shift right assignment a >>= 1 0001
>>>= Shift right zero fill a >>= 1 0011
assignment
<<= Shift left assignment a <<= 1 0110

Relational Operators: The relational operators determine the relationship that


one operand has to the other. Relational operators are the operators which
take numerical values as the input and produces Boolean values as the output.
The following table lists the relational operators:

Operator Purpose Example Result


== Equal to 4 == 1 false
!= Not equal to 4 != 1 true
> Greater than 4>1 true
< Less than 4<1 false
>= Greater than or equal to 4 >= 1 true
<= Less than or equal to 4 <= 1 false

Boolean Logical Operators: Boolean Logical operators are the operators which
take Boolean values as the input and produces Boolean values as the output.
The following table lists the Boolean logical operators:

Narasaraopeta Engineering College :: Narasaraopet Page No. : 8


JAVA PROGRAMMING UNIT I

Operator Purpose Example Result


& Logical AND False & False False
False & True False
True & False False
True & True True
| Logical OR False | False False
False | True True
True | False True
True | True True
^ Logical XOR False ^ False False
(exclusive OR) False ^True True
True ^ False True
True ^ True False
! Logical unary NOT ! Flase True
! True False
&= AND assignment a &= b
False False False
False True False
True False False
True True True
|= OR assignment a |= b
False False False
False True True
True False True
True True True
^= XOR assignment a ^= b
False False False
False True True
True False True
True True False

Short Circuit Logical Operators: Java provides two interesting Boolean


operators not found in many other computer languages. These are secondary
versions of the Boolean AND and OR operators, and are known as short-circuit
logical operators. As you can see from the preceding table, the OR operator
results in true when A is true, no matter what B is. Similarly, the AND operator
results in false when A is false, no matter what B is. If you use the || and &&

Narasaraopeta Engineering College :: Narasaraopet Page No. : 9


JAVA PROGRAMMING UNIT I

forms, rather than the | and & forms of these operators, Java will not bother to
evaluate the right-hand operand when the outcome of the expression can be
determined by the left operand alone. This is very useful when the right-hand
operand depends on the value of the left one in order to function properly.
Ex: if (denom != 0 && num / denom > 10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a
run-time exception when denom is zero. If this line of code were written using
the single & version of AND, both sides would be evaluated, causing a run-
time exception when denom is zero.
Ex: if(c==1 & e++ < 100) d = 100;
Here, using a single & ensures that the increment operation will be applied to
e whether c is equal to 1 or not.
The Assignment Operator: The assignment operator is the single equal sign, =.
It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. The
assignment operator allows to create a chain of assignments.
Ex: int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement. This
works because the = is an operator that yields the value of the right-hand
expression. Thus, the value of z = 100 is 100, which is then assigned to y, which
in turn is assigned to x. Using a ―chain of assignment‖ is an easy way to set a
group of variables to a common value.
The ? Operator: Java includes a special ternary (three-way) operator that can
replace certain types of if-then-else statements. ?. is the ternary operator and
its general form is
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is
evaluated. Both expression2 and expression3 are required to return the same
type, which can‘t be void.
Ex: ratio = denom == 0 ? 0 : num / denom;

Expressions: Expressions are essential building blocks of any Java program.


They are built using values, variables, operators and method calls. An
expression in Java evaluates to a single value.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 10


JAVA PROGRAMMING UNIT I

Precedence rules & Associativity: When the expression has several


operators the precedence rules specify the order in which the operators are
evaluated in an expression. When an expression has more than one operator
with the same precedence the order in which the operators are evaluated is
based on associativity of operators.
Precedence rules: Java has well-defined rules for specifying the order in which
the operators in an expression are evaluated when the expression has several
operators. The order in which the operators are evaluated in an expression is
decided precedence rules. Within an expression operators with higher
precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When an expression has
two operators with the same precedence, the expression is evaluated
according to its associativity. All binary operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated
right to left.
Associativity: When an expression has two operators with the same
precedence, the expression is evaluated according to its associativity. All binary
operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left. For example x = y = z = 17 is
treated as x = (y = (z = 17)), leaving all three variables with the value 17, since
the = operator has right-to-left associativity (and an assignment statement
evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3is
treated as (72 / 2) / 3 since the / operator has left-to-right associativity. The
table below shows all Java operators from highest to lowest precedence, along
with their associativity.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 11


JAVA PROGRAMMING UNIT I

Type Casting: Assigning a value of one type to a variable of another type is


known as Type Casting. Java supports two types of castings. They are
1. Primitive data type casting and
2. Reference type casting.
Primitive data type casting: - Assigning a value of one primitive data type to
another variable of another primitive data type is known as Primitive data type
Casting.
Java primitive data type casting comes with 3 flavors.
1. Implicit casting
2. Explicit casting
3. Boolean casting.
Implicit casting (widening conversion) or Java‘s Automatic Conversions: When
one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place.
Ex: int i =3 ;
long l = i;
Explicit casting (narrowing conversion) or Casting Incompatible Types: When a
variable of higher data type is to be assigned to a variable of lower data type
this is not done implicitly by the JVM and requires explicit casting.
The general form of explicit casting is :
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error
int y = (int) x;
The double x is explicitly converted to int y.
Boolean casting: A boolean value cannot be assigned to any other data type.
Except boolean, all the remaining 7 data types can be assigned to one another
either implicitly or explicitly; but boolean cannot. Thus boolean
is incompatible for conversion. Maximum we can assign a boolean value to
another boolean.
// Demonstrate casts.
class Conversion
{

Narasaraopeta Engineering College :: Narasaraopet Page No. : 12


JAVA PROGRAMMING UNIT I

public static void main(String args[])


{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Let‘s look at each conversion. When the value 257 is cast into a byte variable,
the result is the remainder of the division of 257 by 256 (the range of a byte),
which is 1 in this case. When the d is converted to an int, its fractional
component is lost. When d is converted to a byte, its fractional component is
lost, and the value is reduced modulo 256, which in this case is 67.
Reference type casting
Automatic Type Promotion in Expressions: In addition to assignments, there is
another place where certain type conversions may occur i.e. in expressions.
The Type Promotion Rules: Java defines several type promotion rules that
apply to expressions. They are as follows:
 First, all byte, short, and char values are promoted to int, as just
described.
 Then, if one operand is a long, the whole expression is promoted to long.
 If one operand is a float, the entire expression is promoted to float.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 13


JAVA PROGRAMMING UNIT I

 If any of the operands is double, the result is double.


Ex:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
According to promotion rules all bytes in an expression will be converted to
integer. Thus even the intermediate result i.e. a * b even exceeds the range of
either of its byte operands it will not be a problem. Thus the result of the
expression is integer which is assigned to integer variable.
Ex: byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
During the process of evaluating the expression the b is converted to integer.
So the result on RHS is Integer. As integer cant be assigned to byte , so explicit
casting is required otherwise it gives error. To avoid error the code should be
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.

Statement: A statement is an executable combination of tokens ending with a


semicolon (;) mark. Statements are usually executed in sequential order.
However, it is possible to control the flow of execution by using special
statements. Java implements several types of statements as shown in the
figure.
Labelled Statement: Any Statement may begin with a label. Such labels must
not be keywords, already declared local variables or previously used labels in
this module. Labels in Java are used as the arguments of Jump statements.
Expression Statement: Most statements are expression statements. Java has
seven types of Expression statements Assignment, Pre-Increment, Pre-
Decrement, Post-Increment, Post-Decrement, Method Call and Allocation
Expression.
Selection Statement: These select one of several control flows. There are three
types of selection statements in Java if, if-else, and switch.
Iteration Statement: These specify how and when looping will take place. There
are three types of iteration statements; while, do and for.
Jump Statement: Jump Statements pass control to the beginning or end of the
current block, or to a labelled statement. Such labels must be in the same

Narasaraopeta Engineering College :: Narasaraopet Page No. : 14


JAVA PROGRAMMING UNIT I

block, and continue labels must be on an iteration statement. The three types
of Jump statement are break, continue and return.

Synchronization Statement: These are used for handling issues with


multithreading.
Guarding Statement: Guarding statements are used for safe handling of code
that may cause exceptions (such as division by zero). These statements use the
keywords try, catch, and finally.

Control statements: Control statements are used to change the flow of


execution of a program. Java‘s control statements can be put into the
following categories. They are
1. Selection statements
2. Iteration statements and
3. Jump statements
Iteration statements enable program execution to repeat one or more
statements until the condition is satisfied. Jump statements allow the program
to jump to the required statement within the block.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 15


JAVA PROGRAMMING UNIT I

Selection Statements: Selection statements allow the program to choose


different paths of execution based upon the outcome of an expression or the
state of a variable. There are various types of if statement in java.
a. if statement
b. if-else statement
c. nested if statement
d. if-else-if ladder
e. switch statement
Simple if Statement: The simple if statement initially tests the condition. If the
condition is true it executes the statement-block and moves to the next
statement. If the condition is false it skips the statement-block and directly
moves to the next statement.
Syntax: Flowchart:

if(condition)
{
statement-block;
}
next-statement;

// Program to find the absolute value of the given number


import java.util.Scanner;
public class AbsNum
{
public static void main(String args[])
{
float num;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
num=input.nextFloat();
float num1=num;
if(num<0)
num=-num;
System.out.println("The absolute value of "+num1+" is "+num);
}
}

Narasaraopeta Engineering College :: Narasaraopet Page No. : 16


JAVA PROGRAMMING UNIT I

if-else Statement: The if-else statement is an extension of simple if statement.


If-else statement initially tests the condition. If the condition is true it executes
the true-statement-block and moves to the next statement. If the condition is
false it executes the false-statement-block and moves to the next statement.
In any case , either true-statement-block or false-statement-block is executed
and moves to the next statement.
Syntax: Flowchart:
if(condition)
{
true-statement-block;
}
else
{
false-statement-block;
}
next-statement;

// Program to check whether the given number is even or odd


import java.util.Scanner;
public class EvenOdd
{
public static void main(String args[])
{
int num;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
num=input.nextInt();
if(num %2 == 0)
System.out.println(num+" is an even number");
else
System.out.println(num+" is an odd number");
}
}

Nested – if: When one if statement is nested in another if statement then it is


called as nested if statement.
Syntax: Flowchart:

Narasaraopeta Engineering College :: Narasaraopet Page No. : 17


JAVA PROGRAMMING UNIT I

if(condition1)
{
if(condition2)
{
statement1-block;
}
else
{
statement2-block;
}
}
else
{
statement3-block;
}
next-statement;

// Program to find maximum among three given numbers


import java.util.Scanner;
public class MaxThree
{
public static void main(String args[])
{
float num1,num2,num3, max;
Scanner input = new Scanner(System.in);
System.out.println("Enter any three numbers: ");
num1=input.nextFloat();
num2=input.nextFloat();
num3=input.nextFloat();
if(num1 > num2)
if(num1 > num3)
max = num1;
else
max = num3;
else
if(num2 > num3)

Narasaraopeta Engineering College :: Narasaraopet Page No. : 18


JAVA PROGRAMMING UNIT I

max = num2;
else
max = num3;
System.out.println(―Maximum number is "+max);
}
}
else-if ladder : When one if statement is added in the else part of another if
statement then it is called as else – if ladder statement.
Syntax: Flowchart:

if(condition1)
statement1-block;
else if(condition2)
statement2-block;
else if(condition3)
statement3-block;
statement4-block;
next-statement;

// Program to find roots of a quadratic equation


import java.util.*;
import java.lang.Math;
class QRoots
{
void roots(float a, float b, float c)
{
double d,r1, r2;
if((a==0)||(b==0)||(c==0))
System.out.println("Not a Quadratic Equation");
else
{
d = b*b-4*a*c;
if(d<0)
System.out.println("Roots are Imaginary");
else
if(d==0)
{

Narasaraopeta Engineering College :: Narasaraopet Page No. : 19


JAVA PROGRAMMING UNIT I

r1=-b/(2*a);
System.out.println("Roots are Real and Equal");
System.out.println("Root1=Root2="+r1);
}
else
{
double sqrtd=Math.sqrt(d);
r1=(-b+sqrtd)/(2*a);
r2=(-b-sqrtd)/(2*a);
System.out.println("Roots are Real and Equal");
System.out.println("Root1= "+r1+" Root2= "+r2);
}
}
}
}
public class Quad
{
public static void main(String[] args)
{
float n1,n2, n3 ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the values of Quadratic Equation: ");
n1=input.nextFloat();
n2=input.nextFloat();
n3=input.nextFloat();
QRoots qr = new QRoots();
qr.roots(n1, n2, n3);
}
}
switch statement: The switch statement is a multiway branch statement. It
provides an easy way to select one of the option among several options. It
often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:

switch (expression)
{
case value1: statement1-block;

Narasaraopeta Engineering College :: Narasaraopet Page No. : 20


JAVA PROGRAMMING UNIT I

break;
case value2: statement2-block;
break;
...
case valueN: statementN-block;
break;
default: defaultstatement-block;
}
The expression must be of type byte, short, int, or char. Each of the values
specified in the case statements must be of a type compatible with the
expression. Each case value must be a unique literal that is, it must be a
constant, not a variable. Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is
compared with each of the literal values in the case statements. If a match is
found, the code sequence following that case statement is executed. If none of
the constants matches the value of the expression, then the default statement
is executed. However, the default statement is optional. If no case matches and
no default is present, then no further action is taken. The break statement is
used inside the switch to terminate a statement sequence. When a break
statement is encountered, execution branches to the first line of code that
follows the entire switch statement. This has the effect of ―jumping out‖ of the
switch.
// Program to read day numbers and print name of the day using switch
statement
import java.util.Scanner;
public class DayName
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the day number:");
int dayno=input.nextInt();
switch(dayno)
{
case 1: System.out.println(dayno+"day in the week is Monday");
break;
case 2: System.out.println(dayno+"day in the week is Tuesday");

Narasaraopeta Engineering College :: Narasaraopet Page No. : 21


JAVA PROGRAMMING UNIT I

break;
case 3: System.out.println(dayno+"day in the week is Wednesday");
break;
case 4: System.out.println(dayno+"day in the week is Thursday");
break;
case 5: System.out.println(dayno+"day in the week is Friday");
break;
case 6: System.out.println(dayno+"day in the week is Saturday");
break;
case 7: System.out.println(dayno+"day in the week is Sunday");
break;
default :System.out.println(dayno+"is an Invalid Day Number");
}
}
}
Iteration Statements: Iteration Statement repeats set of instruction until the
condition for termination is met. These statements appear in the source code
only once, but it execute many times. Such kinds of statements are also called
as loops. Iteration Statement in Java are mainly of three types
1. 'while' Statement
2. 'do while' Statement
3. 'for' Statement
while Statement: The while loop is an entry controlled loop. It tests the
condition before executing the loop body. 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. The general form of the while
statement is
while(condition)
{
// body of loop
}
// Program to search an element using Binary Search
import java.util.Scanner;
public class BinarySearch
{

Narasaraopeta Engineering College :: Narasaraopet Page No. : 22


JAVA PROGRAMMING UNIT I

public static void main(String args[])


{
int i, n;
float ele;
float number[] = new float[10];
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers: ");
n = input.nextInt();
System.out.println("Enter " + n + " numbers one by one ");
for (i = 0; i < n; i++)
number[i] = input.nextFloat();
System.out.println("Enter the element to be searched : ");
ele = input.nextFloat();
int lower = 0;
int upper = n - 1;
int middle;
while (lower < upper)
{
middle = (lower + upper) / 2;
if (ele > number[middle])
lower = middle + 1;
else
upper = middle;

}
if (ele == number[lower])
System.out.println(ele + "is found in the list " + lower
+ "position");
else
System.out.println(ele + "is not found in the list");
}
}

do-while: The do-while loop is an exit controlled loop. The do-while loop
always executes its body at least once, because its conditional expression is at
the bottom of the loop. Its general form is
do

Narasaraopeta Engineering College :: Narasaraopet Page No. : 23


JAVA PROGRAMMING UNIT I

{
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the loop
will repeat. Otherwise, the loop terminates.
// Program to print the reverse of a given number
import java.util.Scanner;
class RevNum
{
public static void main(String args[])
{
int num,rev,rem ;
Scanner input = new Scanner(System.in);
System.out.print("Enter any integer number :");
num=input.nextInt();
int num1=num;
rev=0;
do
{
rem = num % 10;
rev=rev*10+rem;
num = num /10;

}while(num!=0);
System.out.print("The reverse number of " + num1+"is "+rev);
}
}

for: Beginning with JDK 5, there are two forms of the for loop. The first is the
traditional form that has been in use since the original version of Java. The
second is the new ―for-each‖ form.
For loop: For loop executes group of Java statements as long as the boolean
condition evaluates to true. For loop combines three elements which we
generally use: initialization statement, boolean expression and increment or
decrement statement. Here is the general form of the traditional for statement:
for(initialization; condition; iteration)

Narasaraopeta Engineering College :: Narasaraopet Page No. : 24


JAVA PROGRAMMING UNIT I

{
// body
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows. When the loop first starts, the initialization
portion of the loop is executed. Generally, this is an expression that sets the
value of the loop control variable, which acts as a counter that controls the
loop. It is important to understand that the initialization expression is only
executed once. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If
this expression is true, then the body of the loop is executed. If it is false, the
loop terminates. Next, the iteration portion of the loop is executed. This is
usually an expression that increments or decrements the loop control variable.
The loop then iterates, first evaluating the conditional expression, then
executing the body of the loop, and then executing the iteration expression
with each pass. This process repeats until the controlling expression is false.
// Program to print factorial of a number
import java.util.Scanner;
class ReturnFact
{

public static void main(String args[])


{
int n,i ;
long f=1;
Scanner input = new Scanner(System.in);
System.out.print("Enter any number: ");
n=input.nextInt();
for(i=1;i<=n;i++)
f*=i;
System.out.println("Factorial of "+n+" is "+f);

}
}

For-Each : A foreach style loop is designed to cycle through a collection of


objects, such as an array, in strictly sequential fashion, from start to finish. The

Narasaraopeta Engineering College :: Narasaraopet Page No. : 25


JAVA PROGRAMMING UNIT I

advantage of this approach is that no new keyword is required, and no


preexisting code is broken. The for-each style of for is also referred to as the
enhanced for loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection, one at a time, from
beginning to end.
// Program to read numbers into an array and search for an element
import java.util.Scanner;
class ForEachSearch
{
public static void main(String args[])
{
int i, n;
Scanner input = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
n=input.nextInt();
float num[] = new float[n];
System.out.println("Enter "+n+" numbers one by one: ");
for(i=0;i<n;i++)
num[i] = input.nextFloat();
System.out.print("Enter number to be searched: ");
float key =input.nextFloat();
boolean found = false;
for(float number: num)
if(number == key)
{
System.out.println(key+" is found in the list ");
found =true;
break;
}
if(found == false)
System.out.println(key+" is not found in the list ");
}
}

Narasaraopeta Engineering College :: Narasaraopet Page No. : 26


JAVA PROGRAMMING UNIT I

Nested Loops: Like all other programming languages, Java allows loops to be
nested. That is, one loop may be inside another. For example, here is a
program that nests for loops:
// Program to sort a given list of numbers
import java.util.*;
public class Sort
{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers: ");
n=input.nextInt();
System.out.println("Enter "+n+" numbers one by one ");
float number[]= new float[n];
for(int i=0;i<n;i++)
number[i]=input.nextFloat();
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(number[j]>number[j+1])
{
float temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
System.out.println("sorted list ia as follows");
for(int i=0;i<n;i++)
System.out.print(" "+number[i]);
}
}
Jump Statements: Java supports three jump statements: break, continue, and
return. These statements transfer control of execution to another part of the
program.
break: In Java, the break statement has three uses. First, as you have seen, it
terminates a statement sequence in a switch statement. Second, it can be used
to exit a loop. Third, it can be used as a ―civilized‖ form of goto. The last two
uses are explained here.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 27


JAVA PROGRAMMING UNIT I

// Program to read marks and find their sum


import java.util.Scanner;
class BreakMarks
{
public static void main(String args[])
{
int i;
float marks,sum=0, avg ;
Scanner input = new Scanner(System.in);
boolean end =false;
System.out.println("Enter marks one by one and press -1 to terminate:");
for(i=1;!end;i++)
{
marks=input.nextFloat();
if(marks>=0)
sum+=marks;
else
break;
}
avg=sum/(i-1);
System.out.println("Total Marks: "+sum);
System.out.println("Average Marks: "+avg);
}
}
Labelled break : The labelled break statement can also be used to construct a
―civilized‖ form of the goto statement. The general form of the labeled break
statement is shown here:
break label;
Most often, label is the name of a label that identifies a block of code. But you
cannot use break to transfer control out of a block that does not enclose the
break statement.
// Program to print triangle of stars
import java.util.Scanner;
class BreakStarTri
{
public static void main(String args[])
{

Narasaraopeta Engineering College :: Narasaraopet Page No. : 28


JAVA PROGRAMMING UNIT I

int i,j,n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many rows:");
n=input.nextInt();
outer:for(i=1;;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(" * ");
if(i==n)
break outer;
}
System.out.println();
}
}
}
Continue: A continue statement causes control to be transferred directly to the
conditional expression that controls the loop.
// Program to print the squareroot of positive numbers
import java.util.Scanner;
class ContSqrt
{
public static void main(String args[])
{
int i;
float num[] = new float[10];
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 numbers to find sqrt:");
for(i=0; i<10;i++)
num[i]=input.nextFloat();
System.out.println("------------------------------");
System.out.println("Number\tSqureroot");
System.out.println("------------------------------");
for(float x: num)
{
if(x>=0)
System.out.println(x+"\t"+Math.sqrt(x));

Narasaraopeta Engineering College :: Narasaraopet Page No. : 29


JAVA PROGRAMMING UNIT I

else
continue;
}
System.out.println("------------------------------");
}
}
Labelled continue: Continue may also specify a label to describe which
enclosing loop to continue.
// Program to print triangle of stars
import java.util.Scanner;
class ContStar
{
public static void main(String args[])
{
int i,j,n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many rows:");
n=input.nextInt();
outer: for(i=1;i<=n;i++)
{
System.out.println();
for(j=1;;j++)
{
System.out.print(" * ");
if(j==i)
continue outer;
}

}
}
}
Return: The last control statement is return. The return statement is used to
explicitly return from a method. That is, it causes program control to transfer
back to the caller of the method.
// Program to print factorial of a number
import java.util.Scanner;
class ReturnFact

Narasaraopeta Engineering College :: Narasaraopet Page No. : 30


JAVA PROGRAMMING UNIT I

{
public long fact(int n)
{
int i ;
long f=1;
for(i=1;i<=n;i++)
f*=i;
return f;
}

public static void main(String args[])


{
Scanner input = new Scanner(System.in);
System.out.print("Enter any number: ");
int n1=input.nextInt();
ReturnFact rf = new ReturnFact();
System.out.println("Factorial of "+n1+" is "+rf.fact(n1));
}
}
Classes: - Class is the logical construct upon which the entire Java language is
built. A class is the basic building block of an object-oriented language such
as Java. It is a template that describes the data and behaviour associated
with instances of that class.
Every class in Java can be composed of the following elements:
 fields, member variables or instance variables — Fields are variables that
hold data specific to each object. For example, an employee might have
an ID number and Name.
 member methods or instance methods — Member methods perform
operations on an object. For example, an employee might have a
method to get his Name and set his Name.
 static fields or class fields — Static fields are common to all object and
they belong to entire class not to an individual object. For example, a
static field EmpCnt within the Employee class could keep track of the
number of objects created for Employee class. Each static field exists only
once in the class, regardless of how many objects are created for that
class.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 31


JAVA PROGRAMMING UNIT I

 static methods or class methods — Static methods are methods that do


not affect a specific object.
 inner classes — Sometimes it is useful to contain a class within another
class. Inner class is useless outside of the class or it cannot be accessed
outside the class.
 Constructors — A special method that is called automatically when a
new object is created.
A simplified general form of a class definition is as shown below:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method class StudDet
} {
} int studno;
String name;
class Stud1 OR void getDet()
{ {
int studno; -----
String name; }
} void printDet()
{
------
}
}

Narasaraopeta Engineering College :: Narasaraopet Page No. : 32


JAVA PROGRAMMING UNIT I

Object: A class is a template for an object, and an object is an instance of a


class.
Creating Objects: When a class is created a new data type is created.
Obtaining objects of a class is a two-step process. First, declare a variable of
the class type. This variable does not define an object. Instead, it is simply a
variable that can refer to an object. Second, an actual and physical copy of
the object should be achieved by using the new operator and assign it to that
variable. The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it. This reference is the
address of the object in memory. Thus, in Java, all class objects must be
dynamically allocated.
class Box
{
double width;
double height;
double depth;
}
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box. After this
line executes, mybox contains the value null, which indicates that it does not
yet point to an actual object. Any attempt to use mybox at this point will result
in a compile-time error. The next line allocates an actual object and assigns a
reference to it to mybox.
After the second line executes, use mybox to refer to the Box object. But in
reality, mybox simply holds the memory address of the actual Box object.

Narasaraopeta Engineering College :: Narasaraopet Page No. : 33


JAVA PROGRAMMING UNIT I

The two step process of Decaling an object can be combined as


Box mybox = new Box();
// Program to demonstrate class with only data members
import java.util.*;
class Stud1
{
int studno;
String name;
}
public class StudDetails
{
public static void main(String args[])
{
Stud1 s1=new Stud1();
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
s1.studno = input.nextInt();
s1.name = input.next();
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+s1.studno);
System.out.println("Name : "+s1.name);

}
}
Methods: Classes usually consist of two things. They are instance variables and
methods. The general form of a method is :
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any
valid type, including class types that are already created. If the method does
not return a value, its return type must be void. The name of the method can
be any legal identifier other than those already used by other items within the
current scope. The parameter-list is a sequence of type and identifier pairs
separated by commas. Parameters are essentially variables that receive the

Narasaraopeta Engineering College :: Narasaraopet Page No. : 34


JAVA PROGRAMMING UNIT I

value of the arguments passed to the method when it is called. If the method
has no parameters, then the parameter list will be empty.
// Program to use class that contains data members and methods
import java.util.*;
class StudDet
{
private int studno;
private String name;
void getDet()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class Stud
{
public static void main(String args[])
{
StudDet s1=new StudDet();
s1.getDet();
s1.printDet();
}
}
Returning a Value: Methods can return value to the calling function. The
general form of the return statement:
return value;
Here, value is the value returned.
// Program to use class which contains a method which returns value
import java.util.*;

Narasaraopeta Engineering College :: Narasaraopet Page No. : 35


JAVA PROGRAMMING UNIT I

public class StudMarks


{
int studno;
String name;
int marks[] = new int[5];
int total;
void getDet()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
System.out.print("Enter Marks in 5 subjects : ");
for(int i=0;i<5;i++)
{
marks[i]=input.nextInt();
}
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
System.out.println("Marks : ");
for(int i=0;i<5;i++)
System.out.println("\tSubject"+ i + " : "+marks[i]);
}
int calTotal()
{
for(int i=0;i<5;i++)
total+=marks[i];
return total;

}
public static void main(String args[])
{
StudMarks s1=new StudMarks();

Narasaraopeta Engineering College :: Narasaraopet Page No. : 36


JAVA PROGRAMMING UNIT I

s1.getDet();
s1.printDet();
System.out.println("Total : "+s1.calTotal());
}
}
Adding a Method That Takes Parameters: While some methods don‘t need
parameters, most do. Parameters allow a method to be generalized. That is, a
parameterized method can operate on a variety of data and/or be used in a
number of slightly different situations. To
// Program to use class which contains methods that take parameters
import java.util.*;
class StudDet
{
private int studno;
private String name;
void setDet(int rno, String sname)
{
studno = rno;
name = sname;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class Stud
{
public static void main(String args[])
{
int rno;
String sname;
StudDet s1=new StudDet();
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
rno = input.nextInt();

Narasaraopeta Engineering College :: Narasaraopet Page No. : 37


JAVA PROGRAMMING UNIT I

sname = input.next();
s1.setDet(rno,sname);
s1.printDet();
}
}
Argument Passing: In general, there are two ways to pass argument to a
method. They are
1. call-by-value
2. call-by-reference
The first way is call-by-value. This approach copies the value of an argument
into the formal parameter of the method. Therefore, changes made to the
parameter in the called method have no effect on the argument in the calling
method. When you pass a primitive type to a method, it is call by value.
The second way an argument can be passed is call-by-reference. In this
approach, a reference to an argument (not the value of the argument) is
passed to the parameter. Inside the called method, this reference is used to
access the actual argument specified in the call. This means that changes made
to the parameter in the called method will affect the argument in the calling
method. When you pass objects to a method, it is call by reference.
// Program to demonstrate call by value technique.
import java.util.Scanner;
class Test
{
void swap(float i, float j)
{
float temp;
temp=i;
i=j;
j=temp;
}
}
class CallByValue
{
float a , b;
public static void main(String args[])
{
Test ob = new Test();

Narasaraopeta Engineering College :: Narasaraopet Page No. : 38


JAVA PROGRAMMING UNIT I

CallByValue cbr = new CallByValue();


Scanner input = new Scanner(System.in);
System.out.println("Enter any two numbers : ");
cbr.a = input.nextFloat();
cbr.b = input.nextFloat();
System.out.println("a and b before swaping: " + cbr.a + " " + cbr.b);
ob.swap(cbr.a, cbr.b);
System.out.println("a and b after swaping: " + cbr.a + " " + cbr.b);
}
}
// Program to demonstrate call by reference technique.
import java.util.Scanner;
class Test1
{
void swap( CallByReference cbr)
{
float temp;
temp=cbr.a;
cbr.a=cbr.b;
cbr.b=temp;
}
}
class CallByReference
{
float a , b;
public static void main(String args[])
{
Test1 ob = new Test1();
CallByReference cbr = new CallByReference();
Scanner input = new Scanner(System.in);
System.out.println("Enter any two numbers : ");
cbr.a = input.nextFloat();
cbr.b = input.nextFloat();
System.out.println("a and b before swaping: " + cbr.a + " " + cbr.b);
ob.swap(cbr );
System.out.println("a and b after swaping: " + cbr.a+ " " + cbr.b);
}

Narasaraopeta Engineering College :: Narasaraopet Page No. : 39


JAVA PROGRAMMING UNIT I

}
Constructor: A constructor is a special method that is used to initialize a newly
created object and is called just after the memory is allocated for the object. It
can be used to initialize the objects ,to required ,or default values at the time
of object creation. It is not mandatory for the coder to write a constructor for
the class
If no user defined constructor is provided for a class, compiler initializes
member variables to its default values.
 numeric data types are set to 0
 char data types are set to null character(‗\0‘)
 reference variables are set to null
Rules for create a Java Constructor
1. It has the same name as the class
2. It should not return a value not even void
// Program using constructor with no arguments
import java.util.Scanner;
class StudDet1
{
private int studno;
private String name;
StudDet1()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentDetails
{
public static void main(String args[])

Narasaraopeta Engineering College :: Narasaraopet Page No. : 40


JAVA PROGRAMMING UNIT I

{
StudDet1 s1=new StudDet1();
s1.printDet();
}
}
Parameterized Constructors: The parameters can also be passed to
constructors.
// Program using parametrized constructor
import java.util.Scanner;
class StudDet12
{
private int studno;
private String name;
StudDet12(int sno1, String sname1)
{
studno = sno1;
name = sname1;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentDetails1
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet12 s1=new StudDet12(sno,sname);
s1.printDet();
}
}

Narasaraopeta Engineering College :: Narasaraopet Page No. : 41


JAVA PROGRAMMING UNIT I

Constructor Overloading: In Java it is possible to define two or more


constructors within the same class as long as their parameter declarations are
different. When this is the case, the constructors are said to be overloaded, and
the process is referred to as constructor overloading.
// Program demonstarting constructor overloading
import java.util.Scanner;
class StudDet12
{
private int studno;
private String name;
StudDet12()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
}

StudDet12(int sno1, String sname1)


{
studno = sno1;
name = sname1;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentDetails1
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();

Narasaraopeta Engineering College :: Narasaraopet Page No. : 42


JAVA PROGRAMMING UNIT I

String sname = input.next();


StudDet12 s1=new StudDet12(sno,sname);
s1.printDet();
StudDet12 s2=new StudDet12();
s2.printDet();
}
}
Cleaning up unused objects - Garbage Collector: In java objects are
dynamically allocated by using the new operator. To delete unused objects
Java takes a different approach; it handles deallocation automatically by using
Garbage Collector. It works like this: when no references to an object exist, that
object is assumed to be no longer needed, and the memory occupied by the
object can be reclaimed. There is no explicit need to destroy objects. Garbage
collection only occurs sporadically (if at all) during the execution of your
program. It will not occur simply because one or more objects exist that are no
longer used.
Class Variables and Methods : Class variables and methods will be used
independently of any object of that class. These are called as static variables
and methods.
static variable
 It is a variable which belongs to the class and not to object(instance)
 Static variables are initialized only once , at the start of the execution .
These variables will be initialized first, before the initialization of any
instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn‘t
need any object
 Syntax : <class-name>.<variable-name>
// Program using static variable
import java.util.Scanner;
class StudDet1234
{
private int studno;
private String name;
static int cnt;
StudDet1234(int studno, String name)
{

Narasaraopeta Engineering College :: Narasaraopet Page No. : 43


JAVA PROGRAMMING UNIT I

this.studno = studno;
this.name = name;
cnt++;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
System.out.println("Number of Objects Created : "+cnt);
}
}
public class StudentStatic
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet1234 s1=new StudDet1234(sno,sname);
s1.printDet();
System.out.println("Enter Student no and name : ");
sno = input.nextInt();
sname = input.next();
StudDet1234 s2=new StudDet1234(sno,sname);
s2.printDet();
}
}
Static Method:
 It is a method which belongs to the class and not to the object(instance)
 A static method can access only static data. It can not access non-static
data (instance variables)
 A static method can call only other static methods and can not call a
non-static method from it.
 A static method can be accessed directly by the class name and doesn‘t
need any object

Narasaraopeta Engineering College :: Narasaraopet Page No. : 44


JAVA PROGRAMMING UNIT I

 Syntax : <class-name>.<method-name>
 A static method cannot refer to "this" or "super" keywords in anyway
// Program using static variable and method
import java.util.Scanner;
class StudDet5
{
private int studno;
private String name;
static int cnt;
StudDet5(int studno, String name)
{
this.studno = studno;
this.name = name;
cnt++;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);

}
static void printCnt()
{
System.out.println("Number of Objects Created : "+cnt);
}

}
public class StudentStaticM
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet5 s1=new StudDet5(sno,sname);

Narasaraopeta Engineering College :: Narasaraopet Page No. : 45


JAVA PROGRAMMING UNIT I

s1.printDet();
System.out.println("Enter Student no and name : ");
sno = input.nextInt();
sname = input.next();
StudDet5 s2=new StudDet5(sno,sname);
s2.printDet();
StudDet5.printCnt();
}
}
Static Block: Static block is mostly used for changing the default values of
static variables. This block gets executed when the class is loaded in the
memory. A class can have multiple Static blocks, which will execute in the same
sequence in which they have been written into the program.
class StaticBlock
{
static int num;
static String mystr;
static
{
num = 97;
mystr = "Static Block in Java";
}
public static void main(String args[])
{
System.out.println("Value of num="+num);
System.out.println("Value of mystr="+mystr);
}
}

Java "THIS" Keyword: Sometimes a method will need to refer to the object
that invoked it. To allow this, Java defines the this keyword. this can be used
inside any method to refer to the current object. That is, this is always a
reference to the object on which the method was invoked. when a local
variable has the same name as an instance variable, the local variable hides the
instance variable. To avoid this problem this keyword can be used.
Keyword 'THIS' in Java is a reference variable that refers to the current object.
The various usage of keyword Java 'THIS' in Java is as per the below,

Narasaraopeta Engineering College :: Narasaraopet Page No. : 46


JAVA PROGRAMMING UNIT I

 It can be used to refer current class instance variable


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance
// Program using this keyword
import java.util.Scanner;
class StudDet123
{
private int studno;
private String name;
StudDet123(int studno, String name)
{
this.studno = studno;
this.name = name;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentThis
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet123 s1=new StudDet123(sno,sname);
s1.printDet();
}
}
Arrays: An array is a group of similar data items referred to by a common
name. An array element is accessed by specifying the name of the array and

Narasaraopeta Engineering College :: Narasaraopet Page No. : 47


JAVA PROGRAMMING UNIT I

the value of the index within square brackets. Depending on number of


subscripts used to refer an array elements, the arrays can be classified as
1. One Dimensional Arrays
2. Multi-Dimensional Arrays
One-Dimensional Arrays: A one-dimensional array is a list of similar data items.
In one-dimensional array one subscript is used to refer an array element. The
general form of a one-dimensional array declaration is
Syntax: type var-name[ ];
Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for the
array determines what type of data the array will hold.
EX: int month_days[];
The above example declares an array named month_days which is capable of
storing integer elements.
To link month_days with an actual, physical array of integers new is a special
operator that allocates dynamic memory for arrays. The general form of new
operator to allocate memory for one-dimensional arrays appears is as follows:
Syntax: array-var = new type[size];
Ex: month_days =new int[12];
It is possible to combine the declaration of the array variable with the
allocation of the array itself, as shown below:
Syntax: type var-name[ ] = new type[size];
Ex: int month_days[] = new int[12];
// Program to search an element using Linear Search
import java.util.Scanner;
public class BinarySearch
{
public static void main(String args[])
{
int i, n;
float ele;
float number[] = new float[10];
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers: ");
n = input.nextInt();
System.out.println("Enter " + n + " numbers one by one ");
for (i = 0; i < n; i++)

Narasaraopeta Engineering College :: Narasaraopet Page No. : 48


JAVA PROGRAMMING UNIT I

number[i] = input.nextFloat();
System.out.println("Enter the element to be searched : ");
ele = input.nextFloat();
int lower = 0;
int upper = n - 1;
int middle;
while (lower < upper)
{
middle = (lower + upper) / 2;
if (ele > number[middle])
lower = middle + 1;
else
upper = middle;
}
if (ele == number[lower])
System.out.println(ele + "is found at " + lower+ "position in the list");
else
System.out.println(ele + "is not found in the list");
}
}
Two-Dimensional Arrays: A two-dimensional array is an array of arrays that
contain similar data items. In two -dimensional array two subscripts are used
to refer an array element. The general form of a two-dimensional array
declaration is
Syntax: type var-name[ ][ ]=new type[ ][ ];
Ex: float a[][] = new float[3][3];
// Program to find the product of two matrices
import java.util.Scanner;
public class MatMul
{
public static void main(String args[])
{
int i,j,k,m, n,p,q;
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of matrix A: ");
m = input.nextInt();
n=input.nextInt();

Narasaraopeta Engineering College :: Narasaraopet Page No. : 49


JAVA PROGRAMMING UNIT I

System.out.println("Enter the size of matrix B: ");


p = input.nextInt();
q=input.nextInt();
if((n==p))
{
float a[][] = new float[m][n];
float b[][]=new float[p][q];
float c[][]=new float[m][q];
System.out.println("Enter " + m * n +"numbers of matrix A: ");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
a[i][j] = input.nextFloat();
System.out.println("Enter " + p * q +"numbers of matrix B: ");
for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
b[i][j] = input.nextFloat();
for (i = 0; i < m; i++)
for (j = 0; j < q; j++)
{
c[i][j]=0;
for (k = 0; k < p; k++)
c[i][j] += a[i][k]*b[k][j];
}
System.out.println("The resultant matrix after multiplication is: " );
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print(c[i][j]+" ");
System.out.println();
}
}
else
System.out.println("Matrix addition not possible");
}
}
Command-Line Arguments: Command-line arguments are used to pass
information into a program while running the program. A command-line

Narasaraopeta Engineering College :: Narasaraopet Page No. : 50


JAVA PROGRAMMING UNIT I

argument is the information that directly follows the program‘s name on the
command line when it is executed. To access the command-line arguments
inside a Java program is quite easy. They are stored as strings in a String array
passed to the args parameter of main( ). The first command-line argument is
stored at args[0], the second at args[1], and so on. All command-line
arguments are passed as strings and must be converted to numeric values for
calculation pupose.
// Program to get day number as command line argument and print dayname
public class CommandLine
{
public static void main(String args[])
{
int dayno=Integer.parseInt(args[0]);
switch(dayno)
{
case 1: System.out.println(dayno+"day in the week is Monday");
break;
case 2: System.out.println(dayno+"day in the week is Tuesday");
break;
case 3: System.out.println(dayno+"day in the week is Wednesday");
break;
case 4: System.out.println(dayno+"day in the week is Thursday");
break;
case 5: System.out.println(dayno+"day in the week is Friday");
break;
case 6: System.out.println(dayno+"day in the week is Saturday");
break;
case 7: System.out.println(dayno+"day in the week is Sunday");
break;
default :System.out.println(dayno+"is an Invalid Day Number");
}
}
}

Narasaraopeta Engineering College :: Narasaraopet Page No. : 51

You might also like