0% found this document useful (0 votes)
4 views122 pages

1 Java Overview

Uploaded by

yokosojiro
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)
4 views122 pages

1 Java Overview

Uploaded by

yokosojiro
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/ 122

Object Oriented

Programming
(CSE-304)

Name: Sandeep Parmar


Java Basics

• History Of Java • Type conversion & casting • Methods


• Java Features • Enumerated types • Static fields and Methods
• Comments • Control Statements • Access Control
• Data Types • Arrays • This Reference
• Variables & Constants • Input & Output • Overloading
Methods/Constructors
• Scope and Life of Variables • Formatting Output
• Recursion
• Operators & Hierarchy • OOP Concepts
• GC
• Expressions • Constructors
• Strings, Enumerations, Generics
History Of Java
History Of java
• Java is an Object-Oriented programming language developed by James Gosling in the
early 1990s.
• The team initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc.
• Originally, C++ was considered to be used in the project, but the idea was rejected for
several reasons(For instance, C++ required more memory).
• Gosling endeavored to alter and expand C++; however, before long surrendered that
for making another stage called Green.
• James Gosling and his team called their project “Greentalk” and its file extension
was .g,t and later became to known as “OAK”.
History Of java
• The name Oak was used by Gosling after an oak tree that remained outside his office. Also,
Oak is an image of solidarity and was picked as a national tree of numerous nations like the
U.S.A., France, Germany, Romania, etc. But they had to later rename it as JAVA as it was
already a trademark by Oak Technologies.

• “JAVA” Gosling and his team did a brainstorming session, and after the session, they came up
with several names such as JAVA, DNA, SILK, RUBY, etc. The name " Java " was decided after
much discussion since it was so unique.

• The name Java originates from a sort of espresso bean, Java. Gosling came up with this name
while having a coffee near his office.

• Java was created on principles like Robust, Portable, Platform Independent, High
Performance, Multithread, etc., Java is used in internet programming, mobile devices, games,
e-business solutions, etc.

• The Java language has experienced a few changes since JDK 1.0, such as various
augmentations of classes and packages to the standard library.

• In Addition to the language changes, considerably more sensational changes have been
made to the Java Class Library throughout the years, which has developed from a couple of
hundred classes in JDK 1.0 to more than three thousand in J2SE 5
Java - Features
1. Simple Syntax
a. Straightforward
b. Very easy to learn
c. Removes complex features like pointers and
multiple inheritance
2. Object Oriented – (Pure object-oriented language)
a. Class
b. Objects
c. Inheritance
d. Encapsulation
e. Abstraction
f. Polymorphism
3. Platform Independent - Java Virtual Machine (JVM)
a. When we write Java code, it is first compiled by
the compiler and then converted into bytecode

b.
(which is platform-independent).
This byte code can run on any platform which has
Features Of Java
JVM installed.
4. Interpreted
Java byte code is translated on the fly to native
machine instructions and is not stored anywhere. The
development process is more rapid and analytical
since the linking is an incremental and light-weight
process.
JVM sits in between the javac compiler and the
underlying hardware, the javac (or any other compiler)
compiler compiles Java code in the Bytecode, which is
understood by a platform specific JVM. The JVM then
compiles the Bytecode in binary using JIT (Just-in-
time) compilation, as the code executes.
5. Scalable
Java can handle both small and large-scale
applications.
Java provides features like multithreading and
distributed computing that allows to manage loads
more easily.
6. Portable
We can simply execute bytecode on any platform with
the help of JVM. Features Of Java
JVMs are available on most devices and that's why we
can run the same Java program on different platform.
7. Secured and Robust
Java is by design highly secure as it is not asking
developers to interact with underlying system
memory or operation system. Bytecode is secure and
several security flaws like buffer overflow, memory
leak are very rare. Java exception handling mechanism
allows developers to handle almost all type of
error/exceptions which can happen during program
execution. Automatic garbage collection helps in
maintaining the system memory space utilization in
check.
Java makes an effort to eliminate error prone
situations by emphasizing mainly on compile time
error checking and runtime checking. Automatic
garbage collection, strong memory management, no
pointers, no direct access to system memory,
exception handling, error handling are some of the
Features Of Java
key features which makes Java a Robust, strong
language to rely on.
8. Memory Management
a. Memory management in Java is automatically handled by
the Java Virtual Machine (JVM).
b. Java garbage collector reclaim memory from objects that are
no longer needed.
c. Memory for objects are allocated in the heap
d. Method calls and local variables are stored in stack.
9. High Performance
Java is faster than old interpreted languages. Java program is first
converted into bytecode which is faster than interpreted code.
10. Multithreading
Multithreading allows multiple threads to run at the same time.
a. Improves CPU utilization and Enhance Performance
b. Important for interactive and high-performance applications,
such as games and real-time systems. Features Of Java
c. Build in support for managing multiple threads.
d. A thread is known as the smallest unit of execution within a
process.
11. Rich Standard Library
a. Pre-built tools and libraries which is known as Java API.
b. Java API is used to cover tasks like file handling,
networking, database connectivity (JDBC), security, etc.
With the help of these libraries developers save a lot of
time and ready to use solutions and can also build a
powerful application.
12. Functional Programming Features
Since Java 8, functional programming features introduced
a. lambda expression let us to write small block of code in a
very easy way without creating full methods.
b. Stream API allows data to be processed easily, Instead of
writing long loops we can just filter, change, or combine
data in a few lines.
c. Functional interfaces are inteface that contains only one
method. They work perfectly with lambda expressions and
help us write flexible and reusable code.
13. Integration with Other Technologies
Can easily work with many languages and tools as well. Java can Features Of Java
connect with C and C++ with the help of Java Native Interface
(JNI). In Java we can use JDBC for database connectivity, Java is
the main language for android development.
14. Support for Mobile and Web Application
a. Java offers support for both web and mobile applications.
b. For web development: Java offers technologies like JSP
and Servlets, along with frameworks like Spring and
Springboot, which makes it easier to build web
applications.
c. For mobile development: Java is the main language for
Android app development. The Android SDK uses special
version of Java and its various tools to build mobile apps
for Android devices.

15. Documentation and Community Support


a. Java provide documentation which includes guides, API
references, and tutorials for easy learning. Java has a
large and active global community contributing to open-
source projects, and resources. This community support
helps developers solve problems and stay updated with
new advancements. Features Of Java
/* Comments Example class Example {
This is my first simple Java program.
Call this file "Example.java". • class is keyword used in Java to declare a new
*/ class

• Important to describe the program • class <class name> {

• The contents of a comment are ignored by the <code lines>


compiler }
• 3 style of comments in Java • Class definition including the variables and
• Multiline (Start with /* end with */) members are define within the { “Open curly
• Single line (Start with //) brace” and end with the } “Closing curly brace”
• Documentation comments (Start with /** end
with */) public static void main(String args[]) {
• This type of comment is used to produce an • It’s a main method of program
HTML file that documents your program.
• This is the line at which the program execution will
start
• All Java program start execution by calling the
main() function.
A First Simple Program
/* }
This is my first simple Java program. Compile Program (Generate Class file)
Call this file "Example.java". C:\>javac Example.java
*/ Run program
class Example { C:\>java Example
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
Void main Statement

- Access specifier. - It is a keyword - It is a keyword - It is a function name - It is arguments/parameter pass


Control the visibility of class - static allows main( ) to be called - Void means nothing - It’s function called when java to the function
member. without having to instantiate a - It tells compiler that main application begins. - If there are no parameters
- public, means that member particular instance of the class. function is returning nothing - Main() and main() both are required for method, you still
may be accessed by code outside -This is necessary since main( ) is different function in Java need to include the empty
the class in which it is declared. called by the Java Virtual parentheses.
- Without main() java will enable
- main( ) must be declared as Machine before any objects are to execute your program -String args[ ] declares a
public, since it must be called by made parameter named args, which is
code outside of its class when an array of instances of the class
the program is started. String
-args receives any command-line
arguments present when the
program is executed

public static void main String args[]

• main( ) is simply a starting place for your program. A complex program will have many number of classes, only one
of which will need to have a main( ) method to get things started.
System.out.println("This is a simple Java program.");
• This line outputs the string “This is a simple Java program.” followed by a new line on the screen.
• Output is accomplished by the built-in println( ) method.
• println( ) displays the string which is passed to it.
• println( ) can be used to display other types of information, too.
• The line begins with System.out. Where System is a predefined class that provides access to the system,
and out is the output stream that is connected to the console.
• All statements in Java end with a semicolon “;”.
Data Types
Primitive Data Type: These are 8 basic building blocks that store simple values
directly in memory.
Non-Primitive Data Types (Object Types): These are reference types that store
memory addresses of objects.
Primitive Data Types Range
Example
Type Description Default Size Range of values
Literals

boolean true or false FALSE 1 byte true, false true, false

byte 8-bit signed integer 0 1 byte (none) -128 to 127

'a', '\u0041', '\101',


char Unicode character(16 bit) \u0000 2 bytes
'\\', '\', '\n', 'β'
0 to 65,535 (unsigned)

short 16-bit signed integer 0 2 bytes (none) -32,768 to 32,767

-2,147,483,648
int 32-bit signed integer 0 4 bytes -2,0,1 to
2,147,483,647
-9,223,372,036,854,770,000
long 64-bit signed integer 0L 8 bytes -2L,0L,1L to
9,223,372,036,854,770,000

float 32-bit IEEE 754 floating-point 0.0f 4 bytes 3.14f, -1.23e-10f ~6-7 significant decimal digits

3.1415d,
double 64-bit IEEE 754 floating-point 0.0d 8 bytes
1.23e100d
~15-16 significant decimal digits
Variables
• It is basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a type, and an optional initializer.
• All variables have a scope, which defines their visibility, and a lifetime.
• All variables must be declared before they can be used
• Declaring a Variable:-
• type identifier [ = value][, identifier [= value] ...] ;

• type is here as datatype it can be primitive or non primitive data type.


• Identifier is the name of the variable
• We can initialized variable by specifying the value using = sign.
• Use , sign to separate/declare the multiple variables
Example Program - Variable
// Demonstrate dynamic initialization. // declares an approximation of pi.
class Example double pi = 3.14159;
{ // the variable x has the value 'x'.
public static void main(String args[]) char x = 'x’;
{ // c is dynamically initialized
double numa = 3.0, num_b = 4.0; double numc1 = Math.sqrt(numa * numa +
num_b * num_b);
// declares 3 integer variables a, b, and c.
System.out.println("Value of var C is " +
int a, b, c; numc1);
// declares three more int var but }
//initializing only d and f.
}
int d = 3, e, f = 5;
byte z = 22; // initializes z.
The Scope and Lifetime of Variables
• Many other computer languages define two general // Demonstrate block scope.
categories of scopes: global and local.
class Scope {
• these traditional scopes do not fit well with Java’s
strict, object-oriented model public static void main(String args[]) {
• Java allows variables to be declared within any block. int x; // known to all code within main
• A block defines a scope.Thus, each time you start a x = 10;
new block, you are creating a new scope.
if(x == 10) { // start new scope
• A scope determines what objects are visible to other
parts of your program. It also determines the lifetime int y = 20; // known only to this block
of those objects.
// x and y both known here.
• Major scopes are those defined by a class and those
defined by a method. System.out.println("x and y: " + x + " " + y);
• As a general rule, variables declared inside a scope x = y * 2;
are not visible (that is, accessible) to code that is
defined outside that scope. Thus, when you declare a }
variable within a scope, you are localizing that
variable and protecting it from unauthorized access // y = 100; // Error! y not known here
and/or modification. // x is still known here.
• Scopes can be nested, means that objects declared
in the outer scope will be visible to code within the //count = 100; // oops! cannot use count before it is declared!
inner scope. int count;
• Within a block, variables can be declared at any
point, but are valid only after they are declared. System.out.println("x is " + x);
}
}
The Scope and Lifetime of Variables
• variables are created when their scope is entered // Demonstrate lifetime of a variable.
and destroyed when their scope is left. class LifeTime {

• This means that a variable will not hold its value public static void main(String args[]) {
once it has gone out of scope. int x;
• A variable declared within a block will lose its value for(x = 0; x < 3; x++) {
when the block is left. Thus, the lifetime of a variable int y = -1; // y is initialized each time block is entered
is limited to its scope.
System.out.println("y is: " + y); // this always prints -1
• If a variable declaration includes an initializer, then y = 100;
that variable will be reinitialized each time the block
in which it is declared is entered. System.out.println("y is now: " + y); }
/* int bar = 1;
• Although blocks can be nested, you cannot declare a
variable to have the same name as one in an outer { // creates a new scope
scope. int bar = 2; // Compile-time error – bar already defined! } */
}}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Constant
• A constant is a variable whose value cannot be changed once it has been initialized.

• To define a variable as a constant, we just need to add the keyword "final" in front of the variable declaration.

• It is not mandatory that we assign values to constants during declaration.

• The naming convention for constants is to use all capital letters with underscores separating words (Best Practice).

final data_type CONSTANT_NAME = value;

final double PI = 3.14159;


class ConstantsDemo { System.out.println("value of a : "+a);
public static void main(String args[]) { //a=200;
final byte var1 = 2; //System.out.println("value of a : "+a);
final float pi; }
pi = 3.14f; }
final int a = 100; //value of var1 : 2
// Displaying values of all variables //value of pi : 3.14
System.out.println("value of var1 : "+var1); //value of a : 100
System.out.println("value of pi : "+pi);
Important terms

- Java is a free-form - It is used for class names, - It is a constant value - In Java, there are a few - There are 50 keywords - Java environment relies
language. method names, and characters that are used currently defined in the on several built-in class
variable names - A constant value in Java is
- Means that no need to created by using a literal as separators Java language libraries.
follow any special - It maybe any descriptive representation of it. - () Parentheses - These keywords, - It contain built-in methods
indentation rules sequence of uppercase that support for I/O, string
and lowercase letters, - 10 (Integer Literal) - {} Braces combined with the syntax
- Program can be write all handling, networking,
numbers, or the - 5.5(Float Literal) - [] Brackets of the operators and
on one line or in multiple graphics etc.
underscore and dollar-sign separators, form the
line - ‘A’(Char Literal) - ; Semicolon foundation of the Java methods: println( ) and
characters
- There is at least one -”My World” (String Literal) - , Comma Language print( )
whitespace character . They must not begin with
a number - True (Boolean Literal) - . Period or DOT - These keywords cannot - Members of the
between each token be used as names for a predefined System class
- whitespace is a space, -Java is case-sensitive, so variable, class, or method. that is automatically
tab, or newline. VALUE is a different included
identifier than Value.

Keywords Java Class


Whitespace Identifiers Literals Separators Libraries
• Separators Symbol Name Purpose

• ( ) Parentheses Used to contain lists of parameters in method definition and invocation. Also used for
defining precedence in expressions, containing expressions in control statements, and surrounding cast
types.
• { } Braces Used to contain the values of automatically initialized arrays. Also used to define a block of code,
for classes, methods, and local scopes.
• [ ] Brackets Used to declare array types. Also used when dereferencing array values.
• ; Semicolon Terminates statements.
• , Comma Separates consecutive identifiers in a variable declaration. Also used to chain statements together
inside a for statement.
• . Period Used to separate package names from subpackages and classes. Also used to separate a variable or
method from a reference variable.
Java Keywords
Operators
Operators
&
Operators Hierarchy
Operators (Arithmetic Operators)
Operator Result
• Arithmetic operators are used in + Addition
mathematical expressions
- Subtraction (also unary minus)
• The operands of the arithmetic operators * Multiplication
must be of a numeric type.
/ Division
• You cannot use them on boolean types, but % Modulus
you can use them on char types, since the
char type in Java is a subset of int. ++ Increment
+= Addition assignment
• The modulus operator, %, returns the
remainder of a division operation. -= Subtraction assignment
*= Multiplication assignment
• It can be applied to floating-point types as well
as integer types. /= Division assignment
%= Modulus assignment
-- Decrement
• Java provides special operators that can be used to combine an arithmetic operation with an assignment.

• var = var op expression; // Can be written as var op= expression;

a = a + 4; // In Java same can be written as a+=4;

• This version += is Addition compound assignment operator

// Demonstrate several assignment operators. System.out.println("c = " + c);


class OpEquals { System.out.println("c = " + c);
public static void main(String args[]) { }
int a = 1; }
int b = 2;
int c = 3, d = 4; //The output of this program is:
a += 5; a = 6
b *= 4; b = 8
c += a * b; c = 51
d %= 6; D = 4
System.out.println("a = " + a);
System.out.println("b = " + b);
• The ++ and the – – are Java’s increment and decrement int x = 1, y = 2;
operators. int x1, y1;
• The increment operator increases its operand by one.
• The decrement operator decreases its operand by one. System.out.println("Before ++x value of x = " + x);
x = x + 1; //can be rewritten as x++; System.out.println("Before y++ value of y = " + y);
x = x - 1; //can be rewritten as x--;
x1 = ++x;
• We can use this operator both as prefix and post fix
y1 = y++;
x = 42; System.out.println("Value Of x after ++x = " + x);
y = ++x; //prefix increment
• In this case, y is set to 43 as the increment occurs before x is System.out.println("Value Of x1 after ++x = " + x1);
assigned to y. System.out.println("Value Of y after y++ = " + y);
x = x + 1; System.out.println("Value Of y1 after y++ = " + y1);
y = x;
x = 42; }
y = x++;//postfix increment }
• The value of x is obtained before the increment operator is
Before ++x value of x = 1
executed, so the value of y is 42.
y = x; Before y++ value of y = 2
x = x + 1; Value Of x after ++x = 2
• In both cases x is set to 43.
Value Of x1 after ++x = 2
// Demonstrate ++.
Value Of y after y++ = 3
class IncDecDemo {
Value Of y1 after y++ = 2
public static void main(String args[]) {
Operators (Bitwise Operators)
Operator Result
~ Bitwise unary NOT
• Java defines several bitwise operators & Bitwise AND
that can be applied to the integer types,
| Bitwise OR
long, int, short, char, and byte
^ Bitwise exclusive OR
• These operators act upon the individual >> Shift right
bits of their operands
>>> Shift right zero fill
• Since the bitwise operators manipulate << Shift left
the bits within an integer, it is important
&= Bitwise AND assignment
to understand what effects such
manipulations may have on a value. |= Bitwise OR assignment
^= Bitwise exclusive OR assignment
• Specifically, it is useful to know how Java
stores integer values and how it >>= Shift right assignment
represents negative numbers. >>>= Shift right zero fill assignment
<<= Shift left assignment
• The bitwise logical operators are &, |, ^, and ~.
• The bitwise operators are applied to each individual bit within each operand.
A B A|B A&B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0

Bitwise NOT
Also called the bitwise complement, the unary NOT operator, ~, inverts all the bits of its operand. For example, the
number 42, in bit pattern:
00101010
becomes
11010101
after the NOT operator is applied.
The Bitwise AND
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all other cases:
00101010 42
& 00001111 15
-------------------
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:

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.

• Notice how the bit pattern of 42 is inverted wherever the second operand has a 1 bit. Wherever the second operand has a 0
bit, the first operand is unchanged.

• You will find this property useful when performing some types of bit manipulations.

00101010 42

^ 00001111 15

------------------

00100101 37
• The left shift operator, <<, shifts all 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.
• For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on the right.

• The right shift operator, >>, shifts all the bits in a value to the right a specified number of times.

• When a value has bits that are “shifted off,” those bits are lost.

• Each time you shift a value to the right, it divides that value by two—and discards any remainder.

00100011>> 2 // 35

00001000 // 8

0100000>>2 // 32

00001000 // 8

• When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous contents of the
top bit. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right.
• The Unsigned Right Shift >>>, shifts all the bits in a value to the right a specified number of times however not filled the top
bit with the previous bit (Sign bit) and filled the zero in higher bit.
11111111 11111111 11111111 11111111 >>> 24 // –1 in binary
00000000 00000000 00000000 11111111 // 255 in binary as an int
• It is useful when you does not represent a numeric value or may not want sign extension to take place, or you are working
with pixel-based values and graphics

• All the binary bitwise operators have a compound form like that of the algebraic operators, which combines the assignment
with the bitwise operation.
Shift the value in a right by four bits
a = a >> 4;
a >>= 4;
a being assigned the bitwise expression a OR b, are equivalent:
a = a | b;
a |= b;
class opBitwiseDemo { position)= " + ans);
public static void main(String args[]) { x=-1;
int x, y,ans; ans=x>>>24;
x=42; System.out.println("Bitwise unsigned right shift for -1 >>> 24
y=15; (24 position)= " + ans);
ans=~x; // It always -(x+1) }
}
System.out.println("Bitwise Not for 42 = " + ans);
ans=x&y; /* Bitwise Not for 42 = -43
System.out.println("Bitwise and for 42 & 15 = " + ans); Bitwise and for 42 & 15 = 10
ans=x|y; Bitwise or for 42 | 15 = 47
System.out.println("Bitwise or for 42 | 15 = " + ans); Bitwise xor for 42 | 15 = 37
ans=x^y; Bitwise left shift for 64 << 2 (2 position)= 256
System.out.println("Bitwise xor for 42 | 15 = " + ans); Bitwise right shift for 35 >> 2 (2 position)= 8
x=64; Bitwise unsigned right shift for -1 >>> 24 (24 position)= 255
ans=x<<2; */
System.out.println("Bitwise left shift for 64 << 2 (2 position)=
" + ans);
x=35;
ans=x>>2;
System.out.println("Bitwise right shift for 35 >> 2 (2
Operators (Relational Operators)

• The relational operators determine the


relationship that one operand has to the
Operator Result
other
== Equal to
• Specifically, they determine equality and != Not equal to
ordering
> Greater than
• The outcome of these operations is a < Less than
boolean value.
>= Greater than or equal to
• The relational operators are most <= Less than or equal to
frequently used in the expressions that
control the if statement and the various
loop statements
Operators (Boolean Logical Operators)
Operator Result
& Logical AND
• The Boolean logical operators shown | Logical OR
here operate only on boolean operands.
^ Logical XOR (exclusive OR)
• All of the binary logical operators
combine two boolean values to form a || Short-circuit OR
resultant boolean value. && Short-circuit AND
• The logical Boolean operators, &, |, and ! Logical unary NOT
^, operate on boolean values in the same
way that they operate on the bits of an &= AND assignment
integer
|= OR assignment
• The logical ! operator inverts the Boolean ^= XOR assignment
state:
== Equal to
!true == false
!= Not equal to
!false == true.
?: Ternary if-then-else
A B A|B A&B A^B !A
False False False False False True
True False True False True False
False True True False True True
True True True True False False

• The Boolean logical operators are &, |, ^, and !.

• Short-Circuit Logical Operators


• if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit.

• AND(&&) short circuit:


• In the case of AND, the expression is evaluated until we get one false result because the result will always be false

• OR(||) short circuit:


• In the case of OR, the expression is evaluated until we get one true result because the result will always be true

• The Assignment Operator


• The assignment operator is the single equal sign, =.
• var = expression;
• x = y = z = 100; // set x, y, and z to 100
The ? Operator

• Java includes a special ternary (three-way) operator that can replace certain types
of if-then-else statements.

expression1 ? expression2 : expression3

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

ratio = denom == 0 ? 0 : num / denom;


Expression

• An expression in Java is a series of operators, variables, and method calls constructed according to the
syntax given, the language for evaluating a single value is as follows:

int marks;
marks = 90;

• Here marks=90 is an expression that returns an int value.

Example:
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
Type Casting

Data Type Conversion


Type Conversion and Casting

• It is to assign a value of one type to a variable of another type


• There are two type of conversion
• Implicit conversion
• Explicit conversion
• If the two types are compatible, then Java will perform the conversion automatically.
• int to long

• There is not all types are compatible, and thus, not all type conversions are implicitly allowed
• double to byte
• We must use a cast, which performs an explicit conversion between incompatible types.
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.
• For example, the int type is always large enough to hold all valid byte values, so no explicit cast
statement is required.
• For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other.
• However, there are no automatic conversions from the numeric types to char or boolean. Also, char
and boolean are not compatible with each other.
• Java also performs an automatic type conversion when storing a literal integer constant into variables
of type byte, short, long, or char.
Casting Incompatible Types
• Opposite to automatic type conversions explicit type conversion is required to store data type that is
not compatible to each other.
• i.e, if you want to assign an int value to a byte variable
• This conversion will not be performed automatically, because a byte is smaller than an int. This kind of
conversion is sometimes called a narrowing conversion, since you are explicitly making the value
narrower so that it will fit into the target type.
• To create a conversion between two incompatible types, we must use a cast. A cast is simply an explicit
type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
int a;
byte b;
// ...
b = (byte) a;
Control
Statements

Selection/Iteration/Jump
• Java programming language uses control statements to cause the flow of execution to advance, and branch
based on changes to the state of a program.
• Java’s program control statements can be put into the following categories:
• Selection: Selection statements allow your program to choose different paths of execution based upon
the outcome of an expression or the state of a variable
• Java supports two selection statements: if and switch
• Iteration: Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops).
• Java’s iteration statements are for, while, and do-while
• Jump: Jump statements allow your program to execute in a nonlinear fashion
• Java supports three jump statements: break, continue, and return.

Control Statement
• These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.
• if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths.

if (condition) statement1; Nested IF The if-else-if Ladder


else statement2; if(i == 10) { if(condition)

if (condition) { if(j < 20) a = b; statement;


statement1; if(k > 100) c = d; // this if is else if(condition)
} else else a = c; // associated with this else statement;
statement3; } else if(condition)
else a = d; // this else refers to if(i == 10) statement;
if (condition) {
statement1; ...
statement2; else
} else { statement;
statement3;
statement4;
}

Selection Statements (if)


// Demonstrate if-else-if statements. season = "Autumn";
class IfElseDemo { else
public static void main(String args[]) { season = "Bogus Month";
int month = 4; // April System.out.println("April is in the " + season + ".");
String season; }
if(month == 12 || month == 1 || month == 2) }
season = "Winter";
else if(month == 3 || month == 4 || month == 5) // Output:-
season = "Spring"; // April is in the Spring.
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
• The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of
your code based on the value of an expression.
• As such, it often provides a better alternative than a large series of if-else-if statements

switch statement: Nested switch Statements


switch (expression) { switch(count) {
case value1: case 1:
// statement sequence switch(target) { // nested switch
break; case 0:
case value2: System.out.println("target is zero");
// statement sequence break;
break; case 1: // no conflicts with outer switch
... System.out.println("target is one");
case valueN: break;
// statement sequence }
break; break;
default: case 2: // ...
// default statement sequence
}
switch Statements
// An improved version of the season program. break;
case 9:
class SwitchDemo { case 10:
public static void main(String args[]) { case 11:
int month = 4; season = "Autumn";
String season; break;
switch (month) { default:
case 12: season = “Invalid Month";
case 1: }
case 2: System.out.println("April is in the " + season + ".");
season = "Winter"; }
break;
}
case 3:
case 4:
break; //Output:-
case 5: //April is in the Spring.
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
• The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is
true.
while(condition) {
// body of loop // Demonstrate the while loop.
} class WhileDemo
• The condition can be any Boolean expression. The body of the {
loop will be executed as long as the conditional expression is
true. public static void main(String args[])
• When condition becomes false, control passes to the next line {
Output:
of code immediately following the loop. int n = 10; tick 10
• The curly braces are unnecessary if only a single statement is while(n > 0) { tick 9
being repeated. tick 8
System.out.println("tick " + n);
• Since the while loop evaluates its conditional expression at tick 7
the top of the loop, the body of the loop will not execute even n--; tick 6
once if the condition is false to begin with } tick 5
int a = 10, b = 20; tick 4
} tick 3
while(a > b)
System.out.println("This will not be displayed"); } tick 2
tick 1
Iteration/loop
Statements (while)
• The do while loop allows you to test the termination expression at the end of the loop rather than at the beginning.
do { // Demonstrate the do - while loop.
// body of loop class DoWhileDemo {
} while (condition); public static void main(String args[]) {
• Each iteration of the do-while loop first executes the body of int n = 10;
the loop and then evaluates the conditional expression.
do {
• If this expression is true, the loop will repeat. Otherwise, the
System.out.println("tick " + n);
loop terminates.
n--; Output:
• Loops, condition must be a Boolean expression. tick 10
} while(n > 0); tick 9
• The do-while loop always executes its body at least once,
because its conditional expression is at the bottom of the loop } tick 8
} tick 7
tick 6
// another way for loop tick 5
do { tick 4
System.out.println("tick " + n); tick 3
tick 2
} while(--n > 0); tick 1
Iteration/loop
Statements (do-while)
• 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(initialization; condition; iteration) { • Next, the iteration portion of the loop is executed. This is
// body usually an expression that increments or decrements the
loop control variable.
}
• The loop then iterates,
• If only one statement is being repeated, there is no need • first evaluating the conditional expression,
for the curly braces.
• then executing the body of the loop,
• The for loop operates as follows. When the loop first • then executing the iteration expression with each
starts, the initialization portion of the loop is executed. pass.
This is loop control variable, which acts as a counter that
controls the loop. • This process repeats until the controlling expression
is false.
• 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.

Iteration/loop
Statements (for)
// Demonstrate the for loop.
class ForTickDemo { • The scope of that variable ends when the for loop end.
public static void main(String args[]) { Using the Comma
int n; class CommaDemo {
for(n=10; n>0; n--)
public static void main(String args[]) {
System.out.println("tick " + n);
} int a, b;
} for(a=1, b=4; a<b; a++, b--) {
System.out.println("a = " + a);
Versatile construct of for loop
System.out.println("b = " + b);
Declaring Loop Control Variables Inside the for Loop }
class ForTickDemo { }
public static void main(String args[]) { }
// here, n is declared inside of the for loop • In this example, the initialization portion sets the values
of both a and b.
for(int n=10; n>0; n--)
• The two comma separated statements in the iteration
System.out.println("tick " + n); portion are executed each time the loop repeats.
}
}
Versatile construct of for loop Initialization or the iteration expression or both may be absent
Some for Loop Variations (conditional expression)
class ForVarDemo {
boolean done = false; public static void main(String args[]) {
for(int i=1; !done; i++) { int i;
boolean done = false;
// ...
i = 0;
if(interrupted()) done = true; for( ; !done; ) { // for( ; ; ) Infinite for loop
} System.out.println("i is " + i);
if(i == 10) done = true;
• In this example, the for loop continues to run until the i++;
boolean variable done is set to true.
}
• It does not test the value of i. }
• One of the most common variations is the conditional }
expression. • Consider as poor style of programming
• this type of approach is useful
• Specifically, this expression does not need to test the loop
control variable against some target value. • if the initial condition is set through a complex expression
elsewhere in the program
• The condition controlling the for can be any Boolean
expression. • if the loop control variable changes in a nonsequential
manner determined by actions that occur within the body
of the loop
• Beginning with JDK 5, a second form of for was
defined that implements a “for-each” style loop.
• A foreach style loop is designed to cycle through a
Traditional Loop
collection of objects, such as an array, in strictly
sequential fashion, from start to finish. int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(type itr-var : collection) statement-block for(int i=0; i < 10; i++) sum += nums[i];
• Here, type specifies the type and itr-var specifies
the name of an iteration variable that will receive For-Each Loop
the elements from a collection, one at a time, from int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
beginning to end. int sum = 0;
• The collection being cycled through is specified by for(int x: nums) sum += x;
collection.
• With each iteration of the loop, the next element in
the collection is retrieved and stored in itr-var. The
loop repeats until all elements in the collection have
been obtained.

The For-Each Version of


the for Loop
• In Java, the break statement has three uses.
 First, To 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.
Using break to Exit a Loop
• By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code
in the body of the loop.
• When a break statement is encountered inside a loop, the loop is terminated, and program control resumes at the next
statement following the loop.
• The break statement can be used with any of Java’s loops, including intentionally infinite loops.
• When used inside a set of nested loops, the break statement will only break out of the innermost loop.
• More than one break statement may appear in a loop. However, Too many break statements have the tendency to de-structure
your code.
• the break that terminates a switch statement affects only that switch statement and not any enclosing loops.
• break was not designed to cancel a loop, only when some sort of special situation occurs we need to use it.

Jump Statements
(break, continue, and
return)
Using break as a Form of Goto
• Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured
manner. However, a few places where the goto is a valuable to control the flow of program.
• For example, the goto can be useful when you are exiting from a deeply nested set of loops. To handle such
situations, Java defines an expanded form of the break statement which can break out of one or more blocks
of code, loop or a switch.
• you can specify precisely where execution will resume, because this form of break works with a label.
break label;
• label is the name of a label that identifies a block of code. This can be a stand-alone block of code but it can
also be a block that is the target of another statement.
• To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon. Once
you have labelled a block, you can then use this label as the target of a break statement.
• When this form of break executes, control is transferred out of the named block. The labelled block must
enclose the break statement, but it does not need to be the immediately enclosing block.
• Doing so causes execution to resume at the end of the labelled block.
• But you cannot use break to transfer control out of a block that does not enclose the break statement.
Using break as a Form of Goto Using break as a Form of Goto
// Using break as a civilized form of goto. // Using break to exit from nested loops
class Break { class BreakLoop4 {
public static void main(String args[]) { public static void main(String args[]) {
boolean t = true; outer: for(int i=0; i<3; i++) {
first: { System.out.print("Pass " + i + ": ");
second: { for(int j=0; j<100; j++) {
third: { if(j == 10) break outer; // exit both loops
System.out.println("Before the break."); System.out.print(j + " ");
if(t) break second; // break out of second block } // inner for loops complete
System.out.println("This won't execute"); System.out.println("This will not print");
} // third block complete } // Outer for loops complete
System.out.println("This won't execute"); System.out.println("Loops complete.");
} // second block complete }
System.out.println("This is after second block."); }
} // first block complete
} // main function complete Output:-
} Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

Output:-
Before the break.
This is after second block.
Using break as a Form of Goto Jump Statement return

// This program contains an error. • The return statement is used to explicitly return from a
class BreakErr { method. It causes program control to transfer back to
public static void main(String args[]) { the caller of the method.
one: for(int i=0; i<3; i++) {
• The return statement immediately terminates the
System.out.print("Pass " + i + ": "); method in which it is executed.
}
for(int j=0; j<100; j++) { // Demonstrate return.
if(j == 10) break one; // WRONG class Return {
System.out.print(j + " "); public static void main(String args[]) {
}
boolean t = true;
}
} System.out.println("Before the return.");
if(t) return; // return to caller
• Since the loop labeled one does not enclose the break System.out.println("This won't execute.");
statement, it is not possible to transfer control out of that }
block.
}
Output:
Before the return.

Jump Statements return


In Java, the continue statement is used inside the loops such as for, while, and do-while to skip the current
iteration and move directly to the next iteration of the loop.
• The continue statement is used when we want to skip a particular condition and continue the rest execution.
Some Points to consider while using Continue statements are mentioned below:
• Java continue statement is used for all types of loops but it is generally used in for, while, and do-while loops.
• In the case of a for loop, the continue keyword forces control to jump immediately to the update statement.
• Whereas in the case of a while loop or do-while loop, control immediately jumps to the Boolean expression.
// Java Program to implement continue // Exit the loop when i == 7
// And break in same loop if (i == 7)
break;
class BreakContinueDemo
{ System.out.print(i + " ");
public static void main(String[] args) }
{ }
for (int i = 1; i <= 10; i++) }
{ Output:
// Skip condition where i==3 12456
if (i == 3)
continue;
Jump Statements
continue
Arrays
• An array is a group of like-typed variables that are referred to by a common name.
• Arrays of any type can be created and may have one or more dimensions.
• A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related
information.
• If you are familiar with C/C++, be careful. Arrays in Java work differently than they do in those languages.
One-Dimensional Arrays :
• It is like a list type variable.
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
int month_days[]; // Integer array
• This declaration means we just create a variable with name month_days and it is a type of array, no array
actually exists. In fact, the value of month_days is set to null, which represents an array with no value.
• To link month_days with an actual, physical array of integers, you must allocate one using new and assign it to
month_days. new is a special operator that allocates memory.

Arrays
array-var = new type[size];
month_days = new int[12];//Month_days array with 12 element
• Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and
array-var is the array variable that is linked to the array.
• To use new to allocate an array, you must specify the type and number of elements to allocate. The elements in
the array allocated by new will automatically be initialized to zero.
• First, you must declare a variable of the desired array type.
• Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable.
That means Java arrays are dynamically allocated.
Access the array element:
• you can access a specific element in the array by specifying its index within square brackets. All array indexes
start at zero
month_days[1] = 28; //assign the value to index 1
System.out.println(month_days[3]); // display the value of index 3

Arrays
// Demonstrate a one-dimensional array. month_days[8] = 30;
class Array { month_days[9] = 31;
public static void main(String args[]) { month_days[10] = 30;
int month_days[]; month_days[11] = 31;
month_days = new int[12]; System.out.println("April has " + month_days[3] + "
month_days[0] = 31; days.");

month_days[1] = 28; }
}
month_days[2] = 31;
month_days[3] = 30; • It is possible to combine the declaration of the array
variable with the allocation of the array itself
month_days[4] = 31;
int month_days[] = new int[12];
month_days[5] = 30;
• Arrays can be initialized when they are declared
month_days[6] = 31;
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
month_days[7] = 31; 31,30, 31 };

Arrays
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
• Java strictly checks to make sure you do not accidentally try to store or reference values outside of the range of
the array.
• The Java run-time system will check to be sure that all array indexes are in the correct range.
• For example, the run-time system will check the value of each index into month_days to make sure that it is
between 0 and 11 inclusive. If you try to access elements outside the range of the array (negative numbers or
numbers greater than the length of the array), you will cause a run-time error

Arrays
// Average an array of values. // Average an array of values.
class Average { class Average {
public static void main(String args[]) { public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0; double result = 0;
int i; for(int i=1; i<=5; i++)
for(i=0; i<5; i++) result = result + nums[i-1];
result = result + nums[i]; System.out.println("Average is " + result / i);
System.out.println("Average is " + result / 5); }
} }
}

Arrays
• Multidimensional Arrays: In Java,
multidimensional arrays are actually arrays
of arrays.
• To declare a multidimensional array
variable, specify each additional index
using another set of square brackets
int twoD[][] = new int[4][5];
• This allocates a 4 by 5 array and assigns it
to twoD. Internally this matrix is
implemented as an array of arrays of int.
// Demonstrate a two-dimensional array. System.out.println();
class TwoDArray { }
public static void main(String args[]) { }
int twoD[][]= new int[4][5]; }
int i, j, k = 0;
for(i=0; i<4; i++) Output:
for(j=0; j<5; j++) { 01234
twoD[i][j] = k; 56789
k++; 10 11 12 13 14
} 15 16 17 18 19
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
• When we allocate memory for a multidimensional array, we need only specify the memory for the first (leftmost)
dimension. We can allocate the remaining dimensions manually
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
• We can allocate the different number of elements for each dimension. Means that the length of each array is
under our control.
// Manually allocate differing size second dimensions. }
class TwoDAgain { for(i=0; i<4; i++) {
public static void main(String args[]) { for(j=0; j<i+1; j++)
int twoD[][] = new int[4][]; System.out.print(twoD[i][j] + " ");
twoD[0] = new int[1]; System.out.println();
twoD[1] = new int[2]; }
twoD[2] = new int[3]; }
twoD[3] = new int[4]; }
int i, j, k = 0; Output:
for(i=0; i<4; i++) 0
for(j=0; j<i+1; j++) { 12
twoD[i][j] = k; 345
k++; 6789
• if you need a very large two-dimensional array that is sparsely populated (that is, one in which not all of the
elements will be used), then an irregular array might be a perfect solution.
• It is possible to initialize multidimensional arrays and To do so, simply enclose each dimension’s initializer within
its own set of curly braces.
• We can use expressions as well as literal values inside of array initializers.

// Initialize a two-dimensional array. System.out.print(m[i][j] + " ");


class Matrix { System.out.println();
public static void main(String args[]) { }
double m[][] = { }
{ 0*0, 1*0, 2*0, 3*0 }, { 0*1, 1*1, 2*1, 3*1 }, }
{ 0*2, 1*2, 2*2, 3*2 }, { 0*3, 1*3, 2*3, 3*3 } Output:
}; 0.0 0.0 0.0 0.0
int i, j; 0.0 1.0 2.0 3.0
for(i=0; i<4; i++) { 0.0 2.0 4.0 6.0
for(j=0; j<4; j++) 0.0 3.0 6.0 9.0
// Demonstrate a three-dimensional array. System.out.println();
class ThreeDMatrix { }}}
public static void main(String args[]) { Output:
int threeD[][][] = new int[3][4][5]; 00000
int i, j, k; 00000
for(i=0; i<3; i++) 00000
for(j=0; j<4; j++) 00000
for(k=0; k<5; k++) 00000
threeD[i][j][k] = i * j * k; 01234
for(i=0; i<3; i++) { 02468
for(j=0; j<4; j++) { 0 3 6 9 12
for(k=0; k<5; k++) 00000
System.out.print(threeD[i][j][k] + " "); 02468
System.out.println(); 0 4 8 12 16
} 0 6 12 18 14
Alternative Array Declaration Syntax:
type[ ] var-name; // to declare arrays
int al[] = new int[3];
int[] a2 = new int[3];

char twod1[][] = new char[3][4]; // char type two dimensional array


char[][] twod2 = new char[3][4]; // char type two dimensional array

int[] nums, nums2, nums3; // create three arrays type integer


int nums[], nums2[], nums3[]; // create three arrays
Input/Output &
Formatting
• Java brings various Streams with its I/O package that helps the user to perform all the input-output operations.
• These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations.
• There are 3 standard stream provide by java which is widely used.

• System.in: This is the standard input stream that is


used to read characters from the keyboard or any
other standard input device.

• System.out: This is the standard output


stream that is used to produce the result of a
program on an output device like the computer
screen.

• System.err: This is the standard error stream that


is used to output all the error data that a program
might throw, on a computer screen or any
standard output device.

Standard Input-Output
Stream
• System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer
screen.
o print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this method in the
form of String.
o println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves
to the start of the next line at the console.
o printf(): This is the easiest of all methods as this is similar to printf in C. System.out.print() and System.out.println() take a single
argument, but printf() may take multiple arguments. This is used to format the output in Java.
• System.out.printf(format, arguments);
• System.out.printf(locale, format, arguments);

o We specify the formatting rules using the format parameter. Rules start with the % character
• %[flags][width][.precision]conversion-character

• s/S formats strings. • The [flags] define standard ways to modify the
• d formats decimal integers. output and are most common for formatting
• f formats floating-point numbers. integers and floating-point numbers.
• t formats date/time values.
• The [width] specifies the field width for
outputting the argument. It represents the
• b/B formats Boolean
minimum number of characters written to the
• c/C formats character
output.
• e formats scientific notation values

Standard Output Stream


// A Java program to demonstrate working of printf() in Java System.out.printf("'%5.2e'%n", 5.1473);
class Example{ }
public static void main(String args[]) { }
int x = 100;
System.out.printf("Printing simple" + " integer: x = %d\n",x); Output:-
// this will print it upto 2 decimal places Printing simple integer: x = 100
System.out.printf( "Formatted with" + " precision: PI = %.2f\n", Formatted with precision: PI = 3.14
Math.PI); Formatted to specific width: n = 5.2000
float n = 5.2f; Formatted to right margin: n = 2324435.2500
// automatically appends zero to the rightmost part of decimal false and FALSE
System.out.printf("Formatted to " + "specific width: n = ' Example' ‘EXAMPLE ‘
%.4f\n",n); sS
n = 2324435.3f; Example of
// here number is formatted from line
//right margin and occupies a width of 20 characters terminator
System.out.printf("Formatted to " + "right margin: n = '5.15e+00'
%20.4f\n",n);
System.out.printf("%b and %B %n", false, false);
System.out.printf("'%15s' '%-10S' %n", "Example", "Example");
System.out.printf("%c %C%n", 's', 's’);
System.out.printf("Example of%nline%nterminator%n");

Standard Output Stream


• System.in: This is the standard input stream that is used to read characters from the keyboard or any other
standard input device.
• However, Java's System.in does not work alone. To read user input with System.in, you must pass it as an
argument to either the constructor of the Scanner class or the constructor of an InputStreamReader
• We can use the System.in.read() to read the input from user.
• System indicates the current computer system.
• in indicates standard input device
• System.in.read indicates reading from a standard input device.
• It is compulsory to use read(byte[]) of input stream-class with try-catch because it throws a checked exception
IOexception.
• So, an alternative instead of try-catch is using throws java.io.IOException.
• System.err: This is the standard error stream that is used to output all the error data that a program might
throw, on a computer screen or any standard output device.
• This stream also uses all the 3 mentioned functions to output the error data:
1. print()
2. println()
3. printf()
Standard Input and Error
Stream
class Input{ import java.io.IOException;
public static void main(String args[]) class Main
throws java.io.IOException {
{ public static void main(String args[])
byte b[]=new byte[50]; {
System.in.read(b); byte b[]=new byte[50];
String s =new String(b); try{
System.out.println(s); System.in.read(b);
} }
} catch(IOException ioe){
System.out.println(ioe);
}
String s=new String(b);// Converts byte into string
System.out.println(s);
}}

Standard Output Stream


OOPs Concepts
OOPs Concepts
Class & Objects
• In object-oriented programming, a class is a blueprint or prototype from which individual objects are created (or, we can
say a class is a data type of an object type).

• In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.

• Using classes, you can create multiple objects with the same behavior instead of writing their code multiple times.
class classname { type methodnameN(parameter-list) {
type instance-variable1; // body of method
type instance-variable2; }
// ... }
type instance-variableN; • The data, or variables, defined within a class are called
instance variables.
type methodname1(parameter-list) {
• Variables defined within a class are called instance variables
// body of method
because each instance of the class (that is, each object of the
} class) contains its own copy of these variables
type methodname2(parameter-list) { • Collectively, the methods and variables defined within a
class are called members of the class.
// body of method
• A class defines a new type of data
} // ...
Class & Objects
• In object-oriented programming, an object is an entity that has two characteristics (states and behavior).
• Some of the real-world objects are car, book, mobile, table, computer, etc.
• An object is a variable of the type class,
• it is a basic component of an object-oriented programming system.
• A class has the methods and data members (attributes), these methods and data members are accessed
through an object. Thus, an object is an instance of a class.
• Declaring Objects:- Obtaining objects of a class is a two-step
process.
• First, you must declare a variable of the class type.
• Second, you must acquire an actual, physical copy of the object
and assign it to that variable.
• Box mybox; // declare reference to object
• mybox = new Box(); // allocate a Box object Class

• The new operator dynamically allocates (that is, allocates at run


time) memory for an object and returns a reference to it.
class-var = new classname( );
Encapsulation
• In an object-oriented approach, encapsulation is a process of binding the data members (attributes) and
methods together.
• it is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code
and the data it manipulates.
• Another way to think about encapsulation is that it is a protective shield that prevents the data from being
accessed by the code outside this shield.
• The encapsulation restricts direct access to important data. The best example of the encapsulation concept is
making a class where the data members are private, and methods are public to access through an object. In
this case, only methods can access those private data.
• 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.
Abstraction
• In object-oriented programming, an abstraction is a technique of hiding internal details and showing
functionalities.
• The abstract classes and interfaces are used to achieve abstraction in Java.
• The real-world example of an abstraction is a Car, the internal details such as the engine, process of starting a
car, process of shifting gears, etc. are hidden from the user, and features such as the start button, gears,
display, break, etc are given to the user. When we perform any action on these features, the internal process
works.
• The abstract keyword is a non-access modifier, used for classes and methods:
• Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).
• Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by
the subclass (inherited from).
Inheritance
• In object-oriented programming, inheritance is a process by which we can reuse the functionalities of existing
classes to new classes.
• In the concept of inheritance, there are two terms base (parent) class and derived (child) class.
• When a class is inherited from another class (base class), it (derived class) obtains all the properties and
behaviors of the base class.
• We are achieving inheritance by using extends keyword. Inheritance is also known as "is-a" relationship.
Polymorphism
• The term "polymorphism" means "many forms".
• In object-oriented programming, polymorphism is useful when you want to create multiple forms with the
same name of a single entity.
• To implement polymorphism in Java, we use two concepts method overloading and method overriding.
• The method overloading known as compile-time polymorphism, is the concept of Polymorphism where more
than one method share the same name with different signature(Parameters) in a class. The return type of
these methods can or cannot be same.
• It is performed in the same class where we have multiple methods with the same name but different
parameters,
• The method overriding is known as run-time polymorphism, is the concept of Polymorphism where method
in the child class has the same name, return-type and parameters as in parent class. The child class provides
the implementation in the method already written.
• It is performed by using the inheritance where we can have multiple methods with the same name in parent
and child classes.
Methods
• This is the general form of a method:
type name(parameter-list) {
// body of method
}
• type specifies the type of data returned by the method
• This can be any valid type, including class types that you create. If the method does not return a value, its
return type must be void.
• The name of the method is specified by name (Identifier).
• The parameter-list is a sequence of type and identifier pairs separated by commas.
• The type of data returned by a method must be compatible with the return type specified by the method.
For example, if the return type of some method is boolean, you could not return an integer.
• The variable receiving the value returned by a method must also be compatible with the return type specified
for the method.
Class/Object/Method Example
// This program includes a method inside the box class. // assign values to mybox1's instance variables
class Box { mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15;
double width, height,depth; // display volume of first box
mybox1.volume();
// display volume of a box // display volume of second box
void volume() { System.out.println(mybox2.volume1(3,6,9));
System.out.print("Volume is "); }
System.out.println(width * height * depth); } }
double volume1(double w, double h, double d) { Output :-
return w * h* d; Volume is 3000.0
}} Volume is 162.0
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
Constructors
• A constructor initializes an object immediately upon creation. It has the same name as the class in which it
resides and is syntactically like a method.
• Once defined, the constructor is automatically called immediately after the object is created, before the new
operator completes.
• Constructors little different than method as they have no return type, not even void. This is because the
implicit return type of a class’ itself.
• It is the constructor’s job to initialize the internal state of an object so that the code creating an instance will
have a fully initialized, usable object immediately.
class-var = new classname( );
Box mybox1 = new Box();
We can add parameters to the constructor.
Constructors
/* Here, Box uses a parameterized constructor to initialize Box mybox1 = new Box(10, 20, 15);

the dimensions of a box. */ Box mybox2 = new Box(3, 6, 9);

class Box { double vol;

double width; double height; double depth; // get volume of first box

// This is the constructor for Box. vol = mybox1.volume();

Box(double w, double h, double d) { System.out.println("Volume is " + vol);

width = w; height = h; depth = d; } // get volume of second box

// compute and return volume vol = mybox2.volume();

double volume() { System.out.println("Volume is " + vol);

return width * height * depth; }}

}} The output from this program is shown here:

class BoxDemo1 { Volume is 3000.0

public static void main(String args[]) { Volume is 162.0


Static Variable & Method
• In Java, the static keyword is used to create variables and methods that belongs to the class rather than any
specific instance of the class.
• Any method or variable that uses the static keyword is referred to as a static variable or static method.
• Static methods can be public or private
• It can be accessed by all instances of the class, but it does not rely on any specific instance, Means there is
only a one copy of the data for whole class.
• Static methods can access static variables directly without the need for an object.
• Static methods cannot access non-static variables (instance) or methods directly.
• Static methods can be accessed directly in both static and non-static contexts.
Syntax to Declare a Static Method
access_modifier static return_type methodName() {
// method body
}
Syntax to Call a Static Method
ClassName.methodName();
Static Variable & Method
Why Use Static Methods?
• To access or modify static variables or perform actions not tied to any instance.
• Useful for utility or helper classes like Collections, Math, etc.
Restrictions on Static Methods
• Non-static data members or non-static methods cannot be used by static methods, and static methods
cannot call non-static methods directly.
• In a static environment, this and super are not allowed to be used.
Why is the main Method Static in Java?
The main method must be static because the JVM does not create an object of the class before invoking it. If it
were a non-static method, JVM would first build an object before calling the main() method, resulting in an extra
memory allocation difficulty.
• If you need to do computation to initialize your static variables, you can declare a static block that gets
executed exactly once, when the class is first loaded.
Difference Between the Static Method and
Instance Method
Instance Methods Static Methods

It requires an object of the class. It does not require an object of the class.

It can access all attributes of a class. It can access only the static attribute of a class.

The methods can be accessed only using object


The method is only accessed by class name.
reference.

Syntax: Objref.methodname() Syntax: className.methodname()

It is an example of pass-by-reference
It's an example of pass-by-value programming.
programming.
Static Variable & Method
// Demonstrate static variables, methods, and blocks. meth(42);
class UseStatic { }
static int a = 3; // static variables. }
• As soon as the UseStatic class is loaded, all of the static
statements are run.
static int b; // static variables.
• First, a is set to 3, then the static block executes, which
static void meth(int x) {// static Method.
prints a message and then initializes b to a * 4 or 12.
System.out.println("x = " + x);
• Then main( ) is called, which calls meth( ), passing 42 to x.
System.out.println("a = " + a); The three println( ) statements refer to the two static
System.out.println("b = " + b); variables a and b, as well as to the local variable x.

} Output:

static { // static block. Static block initialized.

System.out.println("Static block initialized."); x = 42

b = a * 4; a=3

} b = 12

public static void main(String args[]) {


Access Control
• Through encapsulation, we can control what parts of a program (like variables, methods, and even the class itself) can
access the members of a class. By controlling access, we can prevent misuse, build secure and modular code when
designing large applications.

• There are 4 types of access modifiers available in Java:


1. Default - No keyword required
2. Private
3. Protected
4. Public

1. Default Access Modifier

• When no access modifier is specified for a class, method, or data member, it is said to have the default access modifier
by default. This means only classes within the same package can access it.

2. Private Access Modifier

• The private access modifier is specified using the keyword private. The methods or data members declared as private
are accessible only within the class in which they are declared.

• Any other class of the same package will not be able to access these members.

• Top-level classes or interfaces can not be declared as private.


Access Control
3. Protected Access Modifier
• The protected access modifier is specified using the keyword protected.
• The methods or data members declared as protected are accessible within the same package or subclasses in
different packages.
4. Public Access Modifier
• The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all other access modifiers.
• Classes, methods, or data members that are declared as public are accessible from everywhere in the program.
There is no restriction on the scope of public data members.
• Now you can understand why main( ) has always been preceded by the public specifier. It is called by code that is
outside the program—that is, by the Java run-time system.
Access Control
Access Control
/* This program demonstrates the difference between class AccessTest {
public and private. public static void main(String args[]) {
*/ Test ob = new Test();
class Test // These are OK, a and b may be accessed directly
{ ob.a = 10;
int a; // default access ob.b = 20;
public int b; // public access // This is not OK and will cause an error
private int c; // private access // ob.c = 100; // Error!
// methods to access c // You must access c through its methods
void setc(int i) { // set c's value ob.setc(100); // OK
c = i; System.out.println("a, b, and c: " + ob.a + " " + ob.b + "
} " + ob.getc());
int getc() { // get c's value }
return c; }
}
}
• In most real-world classes, we need to allow operations
on data only through methods.
this Keyword
The this Keyword :- This keyword will allow method to refer to the object that invoked it. this can be used inside any
method to refer to the current object

// A redundant use of this.


Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
• In Java to declare two local variables with the same name inside the same or enclosing scopes.
• However, when a local variable has the same name as an instance variable, the local variable hides the instance
variable.
// use of this keyword
Box(double width, double height, double depth) {
this.width = width; // width = width this will not work
this.height = height;
this.depth = depth;
}
Overloading Methods
Overloading Methods:- In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call.
• Overloaded methods must differ in the type and/or number of their parameters.
• While overloaded methods may have different return types, the return type alone is insufficient to distinguish
two versions of a method.
• When Java encounters a call to an overloaded method, it simply executes the version of the method whose
parameters match the arguments used in the call.
• For instance, in C, the function abs( ) returns the absolute value of an integer, labs( ) returns the absolute value of
a long integer, and fabs( ) returns the absolute value of a floating-point value. Since C does not support
overloading, each function has to have its own name, even though all three functions do essentially the same
thing.
• In Java, because each absolute value method can use the same name. Indeed, Java’s standard class library
includes an absolute value method, called abs( ). This method is overloaded by Java’s Math class to handle all
numeric types. Java determines which version of abs( ) to call based upon the type of argument.
Overloading Methods
// Demonstrate method overloading. class Overload {
class OverloadDemo { public static void main(String args[]) {
void test() { OverloadDemo ob = new OverloadDemo();
System.out.println("No parameters"); double result;
} // call all versions of test()
// Overload test for one integer parameter. ob.test();
void test(int a) { ob.test(10);
System.out.println("a: " + a); ob.test(10, 20);
} result = ob.test(123.25);
// Overload test for two integer parameters. System.out.println("Result of ob.test(123.25): " + result);
void test(int a, int b) { }
System.out.println("a and b: " + a + " " + b); }
}
// overload test for a double parameter Output:
double test(double a) { No parameters
System.out.println("double a: " + a); a: 10
return a*a; a and b: 10 20
} double a: 123.25
} Result of ob.test(123.25): 15190.5625
Overloading Methods
// Automatic type conversions apply to overloading. ob.test();
class OverloadDemo { ob.test(10, 20);
void test() { ob.test(i); // this will invoke test(double)
System.out.println("No parameters"); ob.test(123.2); // this will invoke test(double)
} }
// Overload test for two integer parameters. }
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b); Output:
} No parameters
// overload test for a double parameter a and b: 10 20
void test(double a) { Inside test(double) a: 88.0
System.out.println("Inside test(double) a: " + a); Inside test(double) a: 123.2
}
} • Java can automatically convert an integer into a double,
class Overload { and this conversion can be used to call method.
public static void main(String args[]) { • Java will employ its automatic type conversions only if no
OverloadDemo ob = new OverloadDemo(); exact match is found.
int i = 88;
Overloading Constructor
• In addition to overloading normal methods, you can also class OverloadCons {
overload constructor methods. public static void main(String args[]) {
• In fact, for most real-world classes that you create, // create boxes using the various constructors
overloaded constructors will be the norm, not the exception. Box mybox1 = new Box(10, 20, 15);
/* Here, three constructors to initialize dimensions of a box */ Box mybox2 = new Box();
class Box { Box mycube = new Box(7);
double width,height,depth; double vol;
// constructor used when all dimensions specified vol = mybox1.volume(); // get volume of first box
Box(double w, double h, double d) { System.out.println("Volume of mybox1 is " + vol);
width = w; height = h; depth = d; } vol = mybox2.volume(); // get volume of second box
// constructor used when no dimensions specified System.out.println("Volume of mybox2 is " + vol);
Box() { // use -1 to indicate an uninitialized box vol = mycube.volume(); // get volume of cube
width = height = depth= -1; } System.out.println("Volume of mycube is " + vol);
// constructor used when cube is created }
Box(double len) { }
width = height = depth = len; } Output:
// compute and return volume Volume of mybox1 is 3000.0
double volume() { Volume of mybox2 is -1.0
return width * height * depth;} Volume of mycube is 343.0
}
Objects as Parameters
We can pass the object as parameter to the methods. Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
// Objects may be passed to methods. Test ob3 = new Test(-1, -1);
class Test { System.out.println("ob1 == ob2: " +
int a, b; ob1.equals(ob2));
Test(int i, int j) { System.out.println("ob1 == ob3: " +
a = i; ob1.equals(ob3));
b = j; }
} }
// return true if o is equal to the invoking object output:
boolean equals(Test o) { ob1 == ob2: true
if(o.a == a && o.b == b) return true; ob1 == ob3: false
else return false; • One of the most common uses of object parameters
} involves constructors. Frequently, we want to
construct a new object so that it is initially the same as
} some existing object.
class PassOb {
• To do this, we must define a constructor that takes an
public static void main(String args[]) { object of its class as a parameter.
Argument Passing (call-by-value)
Argument Passing:- There are two ways that a computer language can pass an argument to a subroutine.
• The first way is call-by-value. In this approach copies the value of an argument into the formal parameter of the
subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument.
• 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 subroutine, this reference is used to
access the actual argument specified in the call. This means that changes made to the parameter will affect the
argument used to call the subroutine.
• In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the parameter
that receives the argument has no effect outside the method.
// Primitive types are passed by value. System.out.println("a and b before call: " + a + " " + b);
class Test { ob.meth(a, b);
void meth(int i, int j) { System.out.println("a and b after call: " + a + " " + b);
i *= 2; }
j /= 2; } }
}
class CallByValue { Output:
public static void main(String args[]) { a and b before call: 15 20
Test ob = new Test(); a and b after call: 15 20
int a = 15, b = 20;
Argument Passing (call-by-reference)
Argument Passing (call-by-reference):-
• When we pass an object to a method, is effectively call-by-reference. Keep in mind that when we create a
variable of a class type, we are only creating a reference to an object. Hence, when we pass this reference to a
method, the parameter that receives it will refer to the same object as that referred to by the argument. This
effectively means that objects are passed to methods by use of call-by-reference. Changes to the object inside
the method do affect the object used as an argument.
// Objects are passed by reference. class CallByRef {
class Test { public static void main(String args[]) {
int a, b; Test ob = new Test(15, 20);
Test(int i, int j) { System.out.println("ob.a and ob.b before call: " + ob.a + "
a = i; " + ob.b);
b = j; ob.meth(ob);
} System.out.println("ob.a and ob.b after call: " + ob.a + " "
// pass an object + ob.b);
void meth(Test o) { }
o.a *= 2; }
o.b /= 2; Output:
} ob.a and ob.b before call: 15 20
} ob.a and ob.b after call: 30 10
Returning Objects:-
• A method can return any type of data, including class types that we created.
// Returning an object. ob2 = ob1.incrByTen();
class Test { System.out.println("ob1.a: " + ob1.a);
int a; System.out.println("ob2.a: " + ob2.a);
Test(int i) { ob2 = ob2.incrByTen();
a = i; System.out.println("ob2.a after second increase: “ +
} ob2.a);
}
Test incrByTen() { }
Test temp = new Test(a+10);
return temp; Output:
} ob1.a: 2
} ob2.a: 12
class RetOb { ob2.a after second increase: 22
public static void main(String args[]) {
• As we can see, each time incrByTen( ) is invoked, a
Test ob1 = new Test(2); new object is created, and a reference to it is
Test ob2; returned to the calling routine.
Recursion
• Recursion is the process of defining something in terms of itself.
• Recursion is the attribute that allows a method to call itself and method that calls itself is said to be recursive
class Factorial { Factorial f = new Factorial();

// this is a recursive method System.out.println("Factorial of 3 is " + f.fact(3));

int fact(int n) { System.out.println("Factorial of 4 is " + f.fact(4));

int result; System.out.println("Factorial of 5 is " + f.fact(5));

if(n==1) return 1; }}

result = fact(n-1) * n; The output from this program is shown here:

return result; Factorial of 3 is 6

}} Factorial of 4 is 24

class Recursion { Factorial of 5 is 120hod, it will never return. This is a


very common error in working with recursion.
public static void main(String args[]) {
Garbage Collection
Garbage Collection:- Garbage collection in Java is the automated process of deleting code that's no
longer needed or used. This automatically frees up memory space.
• When Java programs run on the JVM, objects are created on the heap, which is a portion of memory
dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector
finds these unused objects and deletes them to free up memory.
• In C/C++, a programmer is responsible for both the creation and destruction of objects. But in Java,
the programmer need not care for all those objects which are no longer in use. Garbage collector
destroys these objects. The main objective of Garbage Collector is to free heap memory by
destroying unreachable objects.
How Does Garbage Collection in Java works?
• Java garbage collection is an automatic process. This process is looking at heap memory, identifying
which objects are in use and which are not, and deleting the unused objects.
• An in-use object, or a referenced object, means that some part of your program still maintains a
pointer to that object.
• An unused or unreferenced object is no longer referenced by any part of your program. So, the
memory used by an unreferenced object can be reclaimed. The programmer does not need to mark
objects to be deleted explicitly.
• 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.
String Class
String is probably the most used class in Java’s class library.
• Every string we create is actually an object of type String. Even string constants are actually String objects.
System.out.println("This is a String, too");
• The string “This is a String, too” is a String constant.
• Another thing to understand about strings is that objects of type String are immutable; once a String object is
created, its contents cannot be altered.
• But if we need to change a string, we can always create a new one that contains the modifications.
• Java defines a peer class of String, called StringBuffer, which allows strings to be altered, so all of the normal
string manipulations are still available in Java.
String myString = "this is a test";
• Java defines one operator for String objects: +. It is used to concatenate two strings.
String myString = "I" + " like " + "Java.";
• We can have arrays of strings, just like you can have arrays of any other type
• The String class contains several methods that we can use
• equals( ) We can test two strings for equality
• length( ) We can obtain the length of a string
• charAt( ) We can obtain the character at a specified index within a string
String Class
// Demonstrating some String methods. else
class StringDemo2 { System.out.println("strOb1 != strOb3");
public static void main(String args[]) { }
String strOb1 = "First String"; }
String strOb2 = "Second String";
String strOb3 = strOb1; This program generates the following output:
System.out.println("Length of strOb1: " + Length of strOb1: 12
strOb1.length()); Char at index 3 in strOb1: s
System.out.println("Char at index 3 in strOb1: " +
strOb1 != strOb2
strOb1.charAt(3));
strOb1 == strOb3
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
Enumerations (enum)
• An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
• we don't need to instantiate an enum using new, it has the same capabilities as other classes.
• Just like classes, you can give them constructors, add instance variables and methods, and even implement interfaces.
• unlike classes, enumerations neither inherit other classes nor can get extended
• The purpose of enum is to representing a group of named constants in a programming language.
• Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes,
command-line flags, etc.
• To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma.
• Enum declaration can be done outside a class or inside a class but not inside a method.
• The first line inside the enum should be a list of constants and then other things like methods, variables, and
constructors.
• According to Java naming conventions, it is recommended that we name constant with all capital letters
• Properties of Enum in Java
• Class Type: Every enum is internally implemented using the Class type.
• Enum Constants: Each enum constant represents an object of type enum.
• Switch Statements: Enum types can be used in switch statements.
• Implicit Modifiers: Every enum constant is implicitly public static final. Since it is static, it can be accessed using
the enum name. Since it is final, enums cannot be extended.
• Main Method: Enums can declare a main() method, allowing direct invocation from the command line.
Enumerations (enum)
// A Java program to demonstrate working on enum case FRIDAY:
import java.util.Scanner; System.out.println("Fridays are better.");
// An Enum class break;
enum Day { case SATURDAY:
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, case SUNDAY:
THURSDAY, FRIDAY, SATURDAY; } System.out.println("Weekends are best.");
// Driver class that contains an object of "day" and main(). break;
public class Test { default:
Day day; System.out.println("Midweek days are so-so.");
// Constructor break; }
public Test(Day day) { }
this.day = day; } public static void main(String[] args) {
// Prints a line about Day using switch String str = "MONDAY";
public void dayIsLike() { Test t1 = new Test(Day.valueOf(str));
switch (day) { t1.dayIsLike();
case MONDAY: }
System.out.println("Mondays are bad."); }
break; // Output : Mondays are bad.
Generics
What Are Generics? The term generics means parameterized types. Parameterized types are
important because they enable you to create classes, interfaces, and methods in which the
type of data upon which they operate is specified as a parameter.
• Using generics, it is possible to create a single class, for example, that automatically works
with different types of data.
• A class, interface, or method that operates on a parameterized type is called generic, as in
generic class or generic method.
• It is important to understand that Java has always given you the ability to create generalized
classes, interfaces, and methods by operating through references of type Object. Because
Object is the superclass of all other classes, an Object reference can refer to any type object.
• Thus, in pre-generics code, generalized classes, interfaces, and methods used Object
references to operate on various types of objects. The problem was that they could not do
so with type safety.
• Generics add the type safety that was lacking. They also streamline the process, because it
is no longer necessary to explicitly employ casts to translate between Object and the type of
data that is actually being operated upon.
• With generics, all casts are automatic and implicit. Thus, generics expand your ability to
reuse code and let you do so safely and easily.
Generics
// T is a type parameter that will be replaced by a real type // to encapsulate the value 88 within an Integer object.
// when an object of type Gen is created. iOb = new Gen<Integer>(88);
class Gen<T> { // Show the type of data used by iOb.
T ob; // declare an object of type T iOb.showType();
// Pass the constructor a reference to an object of type T. // Get the value in iOb. Notice that no cast is needed.
Gen(T o) { int v = iOb.getob();
ob = o; System.out.println("value: " + v);
} System.out.println();
// Return ob. // Create a Gen object for Strings.
T getob() { return ob; } Gen<String> strOb = new Gen<String>("Generics Test");
// Show type of T. // Show the type of data used by strOb.
void showType() { strOb.showType();
System.out.println("Type of T is " + ob.getClass().getName()); // Get the value of strOb. Again, notice that no cast is needed.
}} String str = strOb.getob();
// Demonstrate the generic class. System.out.println("value: " + str);
class GenDemo { }}
public static void main(String args[]) { Output:
// Create a Gen reference for Integers. Type of T is java.lang.Integer
Gen<Integer> iOb; value: 88
// Create a Gen<Integer> object and assign its Type of T is java.lang.String
Thank you

You might also like