Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

BE Java Module -1

The document provides an overview of Object-Oriented Programming (OOP) concepts and Java programming, detailing procedural and structured programming approaches. It covers the history of Java, its evolution from GreenTalk to Java, and outlines various Java versions along with their features. Additionally, it explains Java's lexical issues, data types, operators, and the significance of variables and constants in Java programming.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

BE Java Module -1

The document provides an overview of Object-Oriented Programming (OOP) concepts and Java programming, detailing procedural and structured programming approaches. It covers the history of Java, its evolution from GreenTalk to Java, and outlines various Java versions along with their features. Additionally, it explains Java's lexical issues, data types, operators, and the significance of variables and constants in Java programming.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Module – 1

OOPS CONCEPTS and JAVA PROGRAMMING:


Procedural language: Any programming language in which the programmer
specifies an explicit sequences of steps to follow to produce a result.

Eg:
Step1: get two input
Step 2: compute two numbers
Step 3: display output
Step 4: stop

Structured Programming: An organized approach to programming involving


the use of three basic control structures – sequence, branch and loop and the use
of two-down concepts to decompose main functions into lower level components
for modular coding purposes.

Characteristics of structured programming:


1. Emphasis on doing things (algorithms)
2. Large programs are divided into smaller programs known as functions
3. Most of the functions share global data.
4. Data move openly around the system from function to function.
5. Functions transform data from one form to another.
6. Employs top-down approach in program design.

Object-Oriented Programming (OOPs): A programming paradigm that


represents concepts as “object” that have data fields and associated procedures
known as methods.
Eg: C++, Java, C#, Perl, Python.

Characteristics of Object Oriented Programming:


1. Emphasis is on data rather than procedure.
2. Programs are divided into objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are ties together in the data
structures.
5. Data is hidden and cannot be accessed by external function.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary
8. Follows bottom-up approach in program design.

Object: An object is a real world element which is an identifiable entity with


some characteristics (attributes) and behavior.
Class: A Class is a blueprint or prototype from which objects are created.
Abstraction: The process of representing essential features without including
the background details or explanation.
Encapsulation: The process that facilitates the bundling of data with the
methods operating on that data.
Polymorphism: The ability for a message (function) or data to be processed
in more than one form.
Add(a,b)
Add(a,b,c)
Inheritance: A mechanism by which one class acquires the properties the data
and operations of another class.
Father has curly hairs son has curly
hairs

Dynamic Binding: It is process of linking procedure call to a specific


sequence of function at runtime or during execution of the program.
Java Programming

Source: James Gosling - Wikipedia

History of Java

Source: https://thetapacademy.com/java-programming-language/
Java Name History
GreenTalk
James Gosling was leading a team named as 'Green' team. Target of this team was
to create a new project which can. Initially C++ was the original choice to
develop the project. James Gosling wanted to enhance C++ to achieve the target
but due to high memory usage, that idea was rejected and team started with a new
language initially named as GreenTalk. The file extension used as .gt. Later this
language was termed as Oak and finally to Java.
Oak
James Gosling renamed language to Oak. There was an Oak tree in front of his
office. James Gosling used this name as Oak represents solidarity and Oak tree is
the national tree of multiple countries like USA, France, Romania etc. But Oak
technologies already had Oak as a trademark and James team had to brainstrom
another title for the language.
Finally Java
Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by
the team. James Gosling tabled Java title based on type of espresso coffee bean.
Java is an island in Indonesia where new coffee was discovered termed as Java
coffee. As per James Gosling, Java was among the top choice along with Silk.
Finally Java was selected as it was quite unique and represented the essence of
being dynamic,revolutionary and fun to say.
Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once, Run Anywhere (WORA), providing no-cost run-times on
popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
The latest release of the Java Standard Edition is Java SE 21. With the
advancement of Java and its widespread popularity, multiple configurations were
built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
Java Versions History
Over the period of nearly 30 years, Java has seen many minor and major versions.

Sr.No. Version Date Description

JDK
1 1995 Initial Draft version
Beta

23
2 JDK 1.0 Jan A stable variant JDK 1.0.2 was termed as JDK 1
1996

19
Major features like JavaBeans, RMI, JDBC, inner
3 JDK 1.1 Feb
classes were added in this release.
1997

8 Dec Swing, JIT Compiler, Java Modules, Collections were


4 JDK 1.2
1998 introduced to JAVA and this release was a great success.

8
HotSpot JVM, JNDI, JPDA, JavaSound and support for
5 JDK 1.3 May
Synthetic proxy classes were added.
2000

Image I/O API to create/read JPEG/PNG image were


6 Feb added. Integrated XML parser and XSLT processor
6 JDK 1.4
2002 (JAXP) and Preferences API were other important
updates.

JDK 1.5 30
Various new features were added to the language like
7 or J2SE Sep
foreach, var-args, generics etc.
5 2004

11 1. notation was dropped to SE and upgrades done to


JAVA SE
8 Dec JAXB 2.0, JSR 269 support and JDBC 4.0 support
6
2006 added.
Support for dynamic languages added to JVM. Another
JAVA SE 7 Jul
9 enhancements included string in switch case,
7 2011
compressed 64 bit pointers etc.

18 Support for functional programming added. Lambda


JAVA SE
10 Mar expressions,streams, default methods, new date-time
8
2014 APIs introduced.

21
JAVA SE Module system introduced which can be applied to JVM
11 Sep
9 platform.
2017

Unicode language-tag extensions added. Root


20
JAVA SE certificates, thread local handshakes, support for heap
12 Mar
10 allocation on alternate memory devices etc were
2018
introduced.

Dynamic class-file constants, Epsilon a no-op garbage


JAVA SE 5 Sep
13 collector, local-variable support in lambda parameters,
11 2018
Low-overhead heap profiling support added.

19 Experimental Garbage Collector, Shenandoah: A Low-


JAVA SE
14 Mar Pause-Time Garbage Collector, Microbenchmark Suite,
12
2019 JVM Constants API added.

17
JAVA SE Feature added - Text Blocks (Multiline strings),
15 Sep
13 Enhanced Thread-local handshakes.
2019

17 Feature added - Records, a new class type for modelling,


JAVA SE
16 Mar Pattern Matching for instanceof, Intuitive
14
2020 NullPointerException handling.

15
JAVA SE Feature added - Sealed Classes, Hidden Classes, Foreign
17 Sep
15 Function and Memory API (Incubator).
2020
16 Feature added as preview - Records, Pattern Matching
JAVA SE
18 Mar for switch, Unix Domain Socket Channel (Incubator)
16
2021 etc.

14 Feature added as finalized - Sealed Classes, Pattern


JAVA SE
19 Sep Matching for instanceof, Strong encapsulation of JDK
17
2021 internals by default. New macOS rendering pipeline etc.

22 Feature added - UTF-8 by Default, Code Snippets in


JAVA SE
20 Mar Java API Documentation, Vector API (Third incubator),
18
2022 Foreign Function, Memory API (Second Incubator) etc.

20
JAVA SE Feature added - Record pattern, Vector API (Fourth
21 Sep
19 incubator), Structured Concurrency (Incubator) etc.
2022

Feature added - Scoped Values (Incubator), Record


21
JAVA SE Patterns (Second Preview), Pattern Matching for switch
22 Mar
20 (Fourth Preview), Foreign Function & Memory API
2023
(Second Preview) etc.

19 Feature added - String Templates (Preview), Sequenced


JAVA SE
22 Sep Collections, Generational ZGC, Record Patterns, Pattern
21
2023 Matching for switch etc.

Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators,


Keywords)
White spaces: There has to be at least one whitespace character between each
token, which has not been delineated by an operator or a separator. A whitespace
can be a space, a tab or a newline.
Comments:
• Single-line comments: //
• Multiline comments: /* */
• Documentation comments
The documentation comments are used for writing the documentation of the source
code. The documentation comments start with a forward slash followed by the two
asterisks (/**), end with an asterisk followed by a backward slash (*/), and all lines
between the start and end must start with an asterisk (*).

• The documentation comments are understood by the Javadoc tool and can be used to
create HTML-based documentation.

Java Tokens: it is a smallest individual element in the program


Java tokens has five types: Reserved keywords, identifiers, literals, operators and
separators
Character set: Unicode character set [A-Z, a-z, 0-9 and special character which
are available in keyboard]
Keyword: 50 keywords
Identifiers: Identifiers in Java are symbolic names used for identification. They
can be a class name, variable name, method name, package name, constant name,
and more. However, In Java, There are some reserved words that can not be used
as an identifier.
Rules for Identifiers in Java
There are some rules and conventions for declaring the identifiers in Java. If the
identifiers are not properly declared, we may get a compile-time error. Following
are some rules and conventions for declaring identifiers:
o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and
underscore(_) or a dollar sign ($). for example, @javatpoint is not a valid
identifier because it contains a special character which is @.
o There should not be any space in an identifier. For example, java tpoint is
an invalid identifier.
o An identifier should not contain a number at the starting. For example,
123javatpoint is an invalid identifier.
o An identifier should be of length 4-15 letters only. However, there is no
limit on its length. But, it is good to follow the standard conventions.
o We can't use the Java reserved keywords as an identifier such as int, float,
double, char, etc. For example, int double is an invalid identifier in Java.
o An identifier should not be any query language keywords such as SELECT,
FROM, COUNT, DELETE, etc.

Literals: constant values to be stored in variable


Integral literal, floating point literal, character literal, string and Boolean
‘A’ character, it require 1 byte of memory
“Apple” string it require no of character + 1 byte of memory (i.e 5 character + 1
byte, last bit is used for null character which represent end of string.)
Operators:
Arithmetic: +, -, *, /, %
Relational: <,<=,>,>=,!=,==
Logical: && (AND), || (OR is a pipe symbole), !( not)
Assignment: =
Increment or decrement: ++, --
Conditional: ? : ( exp1?exp2: exp3)
(marks>35? “Pass”: “Try again”;)
Bitwise : &, |, ^ (Exclusive OR), ~ (one complement), << (shift left), >>
(Shift right), >>> (Shift right with zero fill)
Special operators: to indicate a group of code, [] arrays, () functions

We compile the program, we get bytecode.Java interpreter reads bytecode and


translate into machine code
Java Virtual Machine (JVM)
Java program-> Java Compiler->Virtual Machine -> java interpreter -> Machine
Sourcecode byte code

Data types: The data type tells the compiler about the type of data to be stored
and the required memory. To store and manipulate different types of data, all
variables must have specified data types.
• Primitive Data Types
• Reference/Object Data Types

Primitive data types are predefined by the language and named by a keyword.
There are eight primitive data types supported by Java
Type Siz Range Min Max
e in
bits
Byte 8 -128 to -128 127
127
Short 16 -32,768 -32768 32767
to
32,767
Int 32 -231 to -2147483648 2147483647
231-1
Long 64 -263 to - 9223372036854775807
263-1 922337203685477580
8
Float 32 1.4e-045 1.4E-45 3.4028235E38
to
3.4e+03 Sufficient for storing 6 to
8 7 decimal digits
Char 16 0 to
65,535
Boolea 1 True or
n false
Double 8 4.9E-324 1.7976931348623157E30
8
Sufficient for storing 15
decimal digits

Java Reference/Object Data Type


The reference data types are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.

Variables: Variables are containers for storing data values


Constants: Constant is a value that cannot be changed after assigning it. Java
does not directly support the constants. There is an alternative way to define the
constants in Java by using the non-access modifiers static and final.
Scope and life time of variables:
Instance Variables
A variable which is declared inside a class and outside all the methods and blocks
is an instance variable. The general scope of an instance variable is throughout
the class except in static methods. The lifetime of an instance variable is until the
object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked
static is known as a class variable. The general scope of a class variable is
throughout the class and the lifetime of a class variable is until the end of the
program or as long as the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local
variables including the parameters in a method. Scope of a local variable is within
the block in which it is declared and the lifetime of a local variable is until the
control leaves the block in which it is declared.

Operators: Operators in Java are the symbols used for performing specific
operations in Java. Operators make tasks like addition, multiplication, etc which
look easy although the implementation of these tasks is quite complex.
Operators are the building blocks of Java expressions, allowing you to perform
calculations, comparisons

1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non-
primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction

2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement,
or negate a value.
• – : Unary minus, used for negating the values.
• + : Unary plus indicates the positive value (numbers are positive without
this, however). It performs an automatic conversion to int when the type of
its operand is the byte, char, or short. This is called unary numeric
promotion.
• ++ : Increment operator, used for incrementing the value by 1. There are
two varieties of increment operators.

o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is
computed.
• – – : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operators.

o Post-decrement: Value is first used for computing the result and then
decremented.
o Pre-Decrement: The value is decremented first, and then the result is
computed.
• ! : Logical not operator, used for inverting a boolean value.

3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-
left associativity, i.e. value given on the right-hand side of the operator is
assigned to the variable on the left, and therefore right-hand side value must be
declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to
build a shorter version of the statement called a Compound Statement. For
example, instead of a = a+5, we can write a += 5.
• +=, for adding the left operand with the right operand and then assigning it
to the variable on the left.
• -=, for subtracting the right operand from the left operand and then
assigning it to the variable on the left.
• *=, for multiplying the left operand with the right operand and then
assigning it to the variable on the left.
• /=, for dividing the left operand by the right operand and then assigning it
to the variable on the left.
• %=, for assigning the modulo of the left operand by the right operand and
then assigning it to the variable on the left.
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less
than. They return boolean results after the comparison and are extensively used in
looping statements as well as conditional if-else statements. The general format
is,
variable relation_operator value
Some of the relational operators are-
• ==, Equal to returns true if the left-hand side is equal to the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not equal to the right-
hand side.
• <, less than: returns true if the left-hand side is less than the right-hand
side.
• <=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is greater than the right-
hand side.
• >=, Greater than or equal to returns true if the left-hand side is greater than
or equal to the right-hand side.

5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations,
i.e., a function similar to AND gate and OR gate in digital electronics. One thing
to keep in mind is the second condition is not evaluated if the first one is false,
i.e., it has a short-circuiting effect. Used extensively to test for several conditions
for making a decision. Java also has “Logical NOT”, which returns true when the
condition is false and vice-versa
Conditional operators are:
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa

6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three
operands and hence the name Ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute
the statements after the ‘?’ else execute the statements after the ‘:’.

7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e., with all bits
inverted.
8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two. General format-
number shift_op number_of_places_to_shift;
• <<, Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as multiplying the number with some
power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of
the initial number. Similar effect to dividing the number with some power
of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.

9. instanceof operator
The instance of the operator is used for type checking. It can be used to test if an
object is an instance of a class, a subclass, or an interface. General format-
object instance of class/subclass/interface

Operator Hierarchy
The operator precedence represents how two expressions are bind together. In an
expression, it determines the grouping of operators with operands and decides
how an expression will evaluate.
While solving an expression two things must be kept in mind the first is
a precedence and the second is associativity.

Java Operator Precedence Table


The following table describes the precedence and associativity of operators
used in Java.

Precedence Operator Type Associativity

15 () Parentheses Left to Right


[] Array subscript
· Member selection

14 ++ Unary post-increment Right to left


-- Unary post-decrement

13 ++ Unary pre-increment Right to left


-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast

12 * Multiplication Left to right


/ Division
% Modulus

11 + Addition Left to right


- Subtraction

10 << Bitwise left shift Left to right


>> Bitwise right shift with sign
>>> extension
Bitwise right shift with zero
extension

9 < Relational less than Left to right


<= Relational less than or equal
> Relational greater than
>= Relational greater than or
instanceof equal
Type comparison (objects
only)

8 == Relational is equal to Left to right


!= Relational is not equal to

7 & Bitwise AND Left to right

6 ^ Bitwise exclusive OR Left to right

5 | Bitwise inclusive OR Left to right

4 && Logical AND Left to right


3 || Logical OR Left to right

2 ?: Ternary conditional Right to left

1 = Assignment Right to left


+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Arrays:
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store only
a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java
1. arrayRefVar=new datatype[size];

Java Program to illustrate how to declare, instantiate, initialize and traverse


the Java array.

class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
{
System.out.println(a[i]);
}
}
}

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop
prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array)
{
//body of the loop
}

//Java Program to print the array elements using for-each loop


class Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any
array.

//Java Program to demonstrate the way of passing an array to method.


class Testarray2
{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the
array while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array to method.

public class TestAnonymousArray{


//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix
form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

What is the class name of Java array?


In Java, an array is an object. For array object, a proxy class is created whose
name can be obtained by getClass().getName() method on the object.
//Java Program to get the class name of array in Java
class Testarray4{
public static void main(String args[]){
//declaration and initialization of array
int arr[]={4,4,5};
//getting the class name of Java array
Class c=arr.getClass();
String name=c.getName();
//printing the class name of Java array
System.out.println(name);
}}

Copying a Java Array


We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length)

//Java Program to copy a source array into a destination array in Java


class TestArrayCopyDemo {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
Object src, int srcPos,Object dest, int destPos, int length)
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}
Cloning an Array in Java
Since, Java array implements the Cloneable interface, we can create the clone of
the Java array. If we create the clone of a single-dimensional array, it creates the
deep copy of the Java array. It means, it will copy the actual value. But, if we
create the clone of a multidimensional array, it creates the shallow copy of the
Java array which means it copies the references.
//Java Program to clone the array
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);

System.out.println("Printing clone of the array:");


int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);

System.out.println("Are both equal?");


System.out.println(arr==carr);

}}
Few Examples on arrays
1) Java Program to copy all elements of one array into another array
2) Java Program to find the frequency of each element in the array
3) Java Program to left rotate the elements of an array
4) Java Program to print the duplicate elements of an array
5) Java Program to print the elements of an array
6) Java Program to print the elements of an array in reverse order
7) Java Program to print the elements of an array present on even position
8) Java Program to print the elements of an array present on odd position
9) Java Program to print the largest element in an array
10) Java Program to print the smallest element in an array
11) Java Program to print the number of elements present in an array
12) Java Program to print the sum of all the items of the array
13) Java Program to right rotate the elements of an array
14) Java Program to sort the elements of an array in ascending order
15) Java Program to sort the elements of an array in descending order
16) Find 3rd Largest Number in an Array
17) Find 2nd Largest Number in an Array
18) Find Largest Number in an Array
19) Find 2nd Smallest Number in an Array
20) Find Smallest Number in an Array
21) Remove Duplicate Element in an Array
22) Add Two Matrices
23) Multiply Two Matrices
24) Print Odd and Even Number from an Array
25) Transpose matrix
26) Java Program to subtract the two matrices
27) Java Program to determine whether a given matrix is an identity matrix
28) Java Program to determine whether a given matrix is a sparse matrix
29) Java Program to determine whether two matrices are equal
30) Java Program to display the lower triangular matrix
31) Java Program to display the upper triangular matrix
32) Java Program to find the frequency of odd & even numbers in the given
matrix
33) Java Program to find the product of two matrices
34) Java Program to find the sum of each row and each column of a matrix
35) Java Program to find the transpose of a given matrix

Input and Output


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.

3 standard or default streams that Java has to provide which are also most
common in use:

1. System.in: This is the standard input stream that is used to read characters
from the keyboard or any other standard input device.
2. 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.
Here is a list of the various print functions that we use to output statements:
• 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. This method prints the text on the console and the cursor
remains at the end of the text at the console. The next printing takes
place from just here.
Syntax:
System.out.print(parameter);
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. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
printf(): This is the easiest of all methods as this is similar to printf in C. Note
that 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.
1. 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 above-mentioned functions to output the error
data:
• print()
• println()
• printf()
Types of Streams:
• Depending on the type of operations, streams can be divided into two
primary classes:
1. Input Stream: These streams are used to read data that must be
taken as an input from a source array or file or any peripheral
device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as outputs


into an array or file or any output peripheral device. For eg.,
FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.

• Depending on the types of file, Streams can be divided into two


primary classes which can be further divided into other classes as can
be seen through the diagram below followed by the explanations.

1. ByteStream: This is used to process data byte by byte (8 bits).


Though it has many classes, the FileInputStream and the
FileOutputStream are the most popular ones. The
FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination. Here is the
list of various ByteStream Classes:

Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStream This is used for Buffered Output Stream.


Stream class Description

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.


Formatting Output
Java String Format Specifiers

Format Data Type Output


Specifier

%a floating point ( except Returns Hex output of floating-point


BigDecima l) number.

%b Any type " true " if non-null, " false " if null

%c Character Unicode character

%d integer ( incl. byte, short, int, Decimal Integer


long, bigint )

%e floating point Decimal number in scientific notation

%f floating point Decimal number

%g floating point Decimal number, possibly in scientific


notation depending on the precision and
value.

%h any type Hex String of value from hashCode( )


method.

%n None Platform-specific line separator.

%o integer ( incl. byte, short, int, Octal number


long, bigint )

%s any type String value

%t Date/Time ( incl. long, %t is the prefix for Date/Time


Calendar, Date and conversions. More formatting flags are
TemporalAccessor ) needed after this. See Date/Time
conversion below.
%x integer ( incl. byte, short, int, Hex string.
long, bigint )

Control Statements:
A programming language uses control statements to control the flow of execution
of a program based on certain conditions. These are used to cause the flow of
execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:
• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return

1. if: if statement is the most simple decision-making statement. It is used to


decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statements is executed otherwise
not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block of
statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by
default if statement will consider the immediate one statement to be inside its
block. For example,
2. if-else: The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we want to
do something else if the condition is false? Here comes the else statement. We
can use the else statement with the if statement to execute a block of code when
the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
3. nested-if: A nested if is an if statement that is the target of another if or else.
Nested if statements mean an if statement inside an if statement. Yes, java allows
us to nest if statements within if statements. i.e, we can place an if statement
inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
4. if-else-if ladder: Here, a user can decide among multiple options.The if
statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that ‘if’ is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed. There can be as many as ‘else if’ blocks
associated with one ‘if’ block but only one ‘else’ block is allowed with one ‘if’
block.
if (condition)
statement;
else if (condition)
statement;
else
statement;

5. switch-case: The switch statement is a multiway branch statement. It provides


an easy way to dispatch execution to different parts of code based on the value of
the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Looping
Looping in programming languages is a feature which facilitates the execution of
a set of instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition checking
time.

while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
Example:
// Java Program to print Factorial of a number
import java.util.*;
public class Factorial
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int factorial=1,i=1;
System.out.print("Enter number to find factorial- ");
int n= sc.nextInt();
while(i <= n)
{
factorial = factorial*i;
i++;
}
System.out.println("Factorial of "+n +"=" +factorial);
}
}

do while: do while loop is similar to while loop with only difference that it
checks for condition after executing the statements, and therefore is an example
of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);

for loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:
for (initialization condition; testing condition;increment/decrement)
{
statement(s)
}
Example: Java program to print Fibonacci number
import java.util.*;

class Fibonacci{
public static void main(String[] args) {

int firstTerm = 0, secondTerm = 1;


Scanner sc= new Scanner(System.in);
System.out.print("Enter number to find factorial- ");
int n= sc.nextInt();
System.out.println("Fibonacci Series till " + n + " terms:");

for (int i = 1; i <= n; ++i) {


System.out.print(firstTerm + ", ");

// compute the next term


int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

Nested for loop: Nested For Loop is a concept of using a for loop inside another
for loop (Similar to that of using nested if-else).
// Java Program to implement Nested for loop
import java.io.*;

class College {
public static void main(String[] args)
{
// Printing a 1 to 5 (5 times) first loop
for (int i = 1; i <= 5; i++) {
// second loop
for (int j = 1; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output
12345
12345
12345
12345
12345
For Each Loop: Enhanced for loop provides a simpler way to iterate through the
elements of a collection or array. It is inflexible and should be used only when
there is a need to iterate through the elements in a sequential manner without
knowing the index of the currently processed element.

Syntax:
for (T element:Collection obj/array)
{
// loop body
// statement(s)
}

jump: Java supports three jump statements: break, continue and return. These
three statements transfer control to another part of the program.
• Break: In Java, a break is majorly used for:
o Terminate a sequence in a switch statement (discussed above).
o To exit a loop.
o Used as a “civilized” form of goto.
• Continue: Sometimes it is useful to force an early iteration of a loop. That
is, you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. This is, in
effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action.
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

You might also like