1 Java Overview
1 Java Overview
Programming
(CSE-304)
• “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.
• 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
-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] ...] ;
• 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.
• The naming convention for constants is to use all capital letters with underscores separating words (Best Practice).
- 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.
• ( ) 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.
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 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)
• Java includes a special ternary (three-way) operator that can replace certain types
of if-then-else statements.
• Both expression2 and expression3 are required to return the same type, which can’t
be void.
• 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;
Example:
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
Type Casting
• 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.
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.
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.
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.
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
• 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
double width; double height; double depth; // get volume of first box
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.
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:
b = a * 4; a=3
} b = 12
• 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.
• 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.
if(n==1) return 1; }}
}} Factorial of 4 is 24