Beruflich Dokumente
Kultur Dokumente
• Simple
• Syntax is based on C++
• No pointers, No goto, No operator overloading, No
Preprocessor, No global variables.
• Object-Oriented
• Object-oriented means we organize our software as a
combination of different types of objects that
incorporates both data and behaviour.
• Uses OOPs concepts (object, class, Inheritance,
Polymorphism, Encapsulation, etc)
Contd…
Secured
• No explicit pointer
• Programs run inside JVM.
Robust
• Robust simply means strong.
• There is exception handling and type checking
mechanism in java. All these points makes java
robust.
Dynamic:
• Java loads in classes as they are needed,
• it is capable of linking dynamic new classes, methods
and objects.
Compiled and Interpreted:
• Java code is compiled to bytecode.
• Bytecode are interpreted on any platform by JVM.
High Performance
• Bytecode are highly optimised.
• JVM execute Bytecode much faster
Multithreaded
• Multithreading means handling more than one job at a time.
• The main advantage of multi-threading is that it shares the
same memory.
Distributed
• Java programs can be shared over the internet
C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ supports goto statement. Java doesn't support goto statement.
Java doesn't support multiple inheritance
C++ supports multiple inheritance. through class. It can be achieved by
interfaces in java.
Java doesn't support operator
C++ supports operator overloading. overloading.
C++ supports pointers. You can write java has restricted pointer support in java.
pointer program in C++.
C++ supports both call by value and call by Java supports call by value only. There is
reference. no call by reference in java.
Java supports unsigned right shift >>>
C++ doesn't support >>> operator. operator
The Key attributes of OOP’s
class prasad {
public static void main(String[] args)
{
int var1=100;
int var2=var1/2;
System.out.println("var1 contains:“ + var1);
System.out.println("var2 contains:");
System.out.println(var2);
}
} OUTPUT
var1 contains: 100
var2 contains:
50
Contd…
class prasad {
public static void main(String[] args)
{
int var1=100;
int var2=var1/2;
System.out.println("var1 contains:“ + var1);
System.out.print("var2 contains:");
System.out.println(var2);
}
} OUTPUT
var1 contains: 100
var2 contains:50
JAVA KEYWORDS
• In the Java programming language, a keyword
is any one of 55 reserved words that have a
predefined meaning in the language; because
of this, programmers cannot use keywords as
names for variables, methods, classes, or as
any other identifier.
The Java Keywords
Although const and goto are reserved words, they are not currently part of the
Java language.
Java Identifiers:
char Character
int Integer
Float
• float
• double
Logical • boolean
Character • char
Data types
Primitive types
• byte 1 bytes 0
Integer
• short 2 bytes 0
• int 4 bytes 0
• long 8 bytes 0L
Float
• float 4 bytes 0.0f
• double 8 bytes 0.0d
• Example:
• Animal animal = new Animal("giraffe");
Literals
• Initializing a variable:
• follow the variable’s name with an equal sign and the value
being assigned.
• The general form of initialization is shown here
• type var=value;
• Ex:
• int count=10;
• char ch =‘a’;
• float f=1.2;
• When declaring two or more variables of the same type
using a comma-separated list.
• Ex: int a,b=10,c,d=15;
Dynamic Initialization
• Java allows variables to be initialized dynamically, using
any expression valid at the time the variable is declared.
• Ex:
public class Main
{
public static void main(String args[])
{
// c is dynamically initialized
double c = Math.sqrt(2 * 2);
System.out.println("c is " + c);
}
}
The scope and lifetime of variables
• Ex:
class Demo
{
public static void main ( String [ ] args ) {
int x =10;
if (true) { // creates new scope
int y = 20;
System.out.println ( y ); // OK
}
System.out.println ( y ); // ERROR, not in scope
System.out.println ( x ); // OK
}
}
Operators
++ -- ~ ! not associative
* / % left to right
+ - left to right
>> >>> << left to right
> >= < <= not associative
== != left to right
• = 1+2-3*4/5
• = (1 + 2) - ((3 * 4) / 5)
• = 3 - (12/5)
• =3 - 2 The result of the integer division, 12/5, is 2 .
• =1
• adding parentheses to reduce ambiguity does not
negatively affect your program.
Expressions
Ex:
class rnsit
{
public static void main(String[] args)
{
byte b; int i;
b=10;
i=b * b; // ok, no cast needed
b=10;
b=(byte)(b* b); // cast needed
System.out.println(“ i and b:” +i+ “ “ +b);
}
}
Contd….
• No cast is needed when b*b=i ,because b is
promoted to int when the expression is evaluated.
• The same sort of situation also occurs when
performing operations on char.
• Ex:
• char ch1=‘a’,ch2=‘b’;
• ch1=(char)(ch1 + ch2)
• Without the cast, the resulting of adding ch1 and ch2
would be int, which can’t be assigned to a char.
Module 1
Program Control Statements
import java.io.*;
class ex13
{
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student11 s1 = new Student11(111,"Kiran");
Student11 s2 = new Student11(222,"Ajay");
s1.display();
s2.display();
}
}
EX2:
class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
this.m();
}
}
class TestThis4
{
public static void main(String args[]){
A a=new A();
a.n();
}}
Arrays:
• array is a collection of similar type of elements that
have contiguous memory location.
• Java array is an object that contains elements of
similar data type.
• It is a data structure where we store similar
elements. We can store only fixed set of elements in
a java array.
• Array in java is index based, first element of the array
is stored at 0 index.
Contd…..
• Advantage of Java Array
• Code Optimization: It makes the code optimized, we
can retrieve or sort the data easily.
• Random access: We can get any data located at any
index position.
• Disadvantage of Java Array
• Size Limit: We can store only fixed size of elements in
the array. It doesn't grow its size at runtime.
Contd….
• There are two types of array.
Single or One Dimensional Array
Multidimensional Array
• A One Dimensional Array is a list of related variables.
Such lists are common in programming .
• To declare a one-dimensional array, you will use this
general form:
type[] array-name=new type[size];
• Here, type declares the element type of the array.
(The element type is also sometimes referred to as
the base type).
Contd….
• The element type determines the data type of each
element contained in the array.
• The number of elements that the array will hold is
determined by size.
• Since arrays are implemented as objects,
• The creation of array is two-step process.
• First, you declare an array reference variable.
• Second, you allocate memory for the array, assigning
the reference to that memory to the array variable.
• Thus, arrays are dynamically allocated using the new
operator.
Contd….
• Ex:
• int[] sample=new int[10];
• This declaration works like an object declaration.
• The sample variable hold a reference to the memory
allocated by new.
• This memory is large enough to hold 10 elements of
type int.
• It is possible to break the preceding declaration in
two.
int[] sample;
sample=new int[10];
Contd….
• Ex:
class ArrayDemo
{
public static void main(String[] args)
{
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
{
sample[i] = i;
System.out.println("This is sample[" + i + "]: " + sample[i]);
}
}
}
• Ex2:
class MinMax {
public static void main(String[] args) {
int[] nums = new int[5];
int min, max;
nums[0] = 99;nums[1] = 200;nums[2] = 100;
nums[3] = 18;nums[4] = -978;
min = nums[0];
max = nums[0];
for(int i=1; i < 5; i++) {
if(nums[i] < min) min = nums[i];
if(nums[i] > max) max = nums[i];
}
System.out.println("min and max: " + min + " " + max);
}
}
Contd….
• Arrays can be initialized when they are created.
• The general form for initializing a one-dimensional array
is,
type[] array-name={val1,val2,val3…..valN}
• Here, the initial value are specified by val1 through valN.
• They are assigned in sequence, left to right, in index
order.
• Java automatically allocates an array large enough to
hold the initializers that you specify.
• There is no need to explicitly use the new operator.
• Ex:
class MinMax2
{
public static void main(String[] args)
{
int[] nums = { 99,5623, 463, 287, 49 };
int min, max;
min = nums[0];
max = nums[0];
for(int i=1; i < 5; i++)
{
if(nums[i] < min) min = nums[i];
if(nums[i] > max) max = nums[i];
}
System.out.println("Min and max: " + min + " " + max);
}
}
Multidimensional arrays
• In java, multidimensional array or two dimensional
array is a array of arrays.
• A two-dimensional array can be thought of as
creating a table of data, with the data organized by
row and column.
• An individual item of data is accessed by specifying
its row and column position.
• To declare a two-dimensional array, you must specify
the size of both dimensions.
• int [][] table=new int[10][20];
Here table is declared to be a two-dimensional array of int with the size
10 and 20.
Ex:
class TwoD {
public static void main(String[] args) {
int t, i;
int[][] table = new int[3][4];
for(t=0; t < 3; t++) {
for(i=0; i < 4; i++) {
table[t][i] = (t*4)+i+1;
System.out.print(table[t][i] + " ");
}
System.out.println();
}
}
}
Initializing multidimensional Arrays
• A multidimensional array can be initialized by enclosing
each dimension’s initializer list within its own set of braces.
• The general form is
type[][] array-name={
{val,val,val…..val},
{val,val,val…..val},
….
…..
{val,val,val…..val}
};
Contd…..
• Here, val indicates an initialization value.
• Each inner block designates a row.
System.out.println(“Biggest = ” + big) ;
}
}
Alternative array declaration systax
• There is a second form that can be used to declare an
array.
type var-name[];
• Here the square brackets follows the name of the array
variable, not the type specifier.
• ex: int rnsit[]=new int[5];
• int[] rnsit=new int[5];
• This alternative declaration lets you declare both array
and nonarray variables of the same type in a single
declaration.
• Ex: int alpha,beta[],gamma;
Assigning array references
• As with other objects, when you assign one array reference variable to
another, you are simply changing what objects that variables refers to.
Ex:
class AssignARef
{
public static void main(String[] args)
{
int i;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for(i=0; i < 10; i++)
nums1[i] = i;
for(i=0; i < 10; i++)
nums2[i] = -i; Contd.....
System.out.print("Here is nums1: ");
for(i=0; i < 10; i++)
System.out.print(nums1[i] + " ");
System.out.println();
System.out.print("Here is nums2: ");
for(i=0; i < 10; i++)
System.out.print(nums2[i] + " ");
System.out.println();
nums2 = nums1;
System.out.print("Here is nums2 after assignment: ");
for(i=0; i < 10; i++)
System.out.print(nums2[i] + " ");
System.out.println();
}
}
The for-each style for loop
• A for-each loop cycles through a collection of
objects, such as an array, in strictly sequential fashion
from start to finish.
• The general form of the for-each style is
• for(type itr-var:collection)statement-block
• Here, type specifies the type.
• itr-val specifies the name of an iteration variable that
will receive the elements from a collection, one at a
time, from beginning to end.
• The collection being cycled through is specified by
collection.
• Ex:1
class ForEach
{
public static void main(String[] args)
{
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums)
{
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
• Ex2:
class Big {
public static void main (String [] arg)
{
int [] myArr = { 45, 5, 34, 8 } ;
int big = myArr[0];
for( int num : myArr)
if ( big<num )
big = num;
System.out.println(“Bigest = ” + big) ;
}
}
Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the
runtime unused memory automatically.
• In other words, it is a way to destroy the unused
objects.
• To do so, we were using free() function in C language
and delete() in C++.
• But, in java it is performed automatically.
• So, java provides better memory management.
• when no references to an object exist, that object is
assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
How can an object be unreferenced?
• There are many ways:
• By nulling the reference
Employee e=new Employee();
e=null;
• By assigning a reference to another
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
//now the first object referred by e1 is availabl
e for garbage collection
• By anonymous object.
new Employee();
finalize() method
• The finalize() method is invoked each time before the object
is garbage collected.
• This method is called finalize(),and it can be used in very
specialized case to ensure that an object terminates cleanly.
• To add a finalizer to class, you must define the finalize()
method.
• The general form:
protected void finalize()
{
//code
}
• It is important to understand that finalize( ) is only called just
prior to garbage collection.