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

Introduction Java

The document provides an overview of Java including that it was developed by Sun Microsystems in 1995 and is a platform independent language that compiles code to bytecode that can run on any Java Virtual Machine. It discusses key Java concepts like bytecode, data types, variables, operators, and input/output and compares Java to C++ highlighting differences in memory management, threads, and inheritance. The document also provides examples of Java code demonstrating variables, operators, and input/output.

Uploaded by

arnav preet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Introduction Java

The document provides an overview of Java including that it was developed by Sun Microsystems in 1995 and is a platform independent language that compiles code to bytecode that can run on any Java Virtual Machine. It discusses key Java concepts like bytecode, data types, variables, operators, and input/output and compares Java to C++ highlighting differences in memory management, threads, and inheritance. The document also provides examples of Java code demonstrating variables, operators, and input/output.

Uploaded by

arnav preet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Introduction Java

Prof AK Bhateja
Java
• Java developed by Sun Microsystems and
released in 1995.
• Java is Write Once, Run Anywhere.
• Every 6 months, Oracle releases out new Java
versions.
• Java SE 12 was released in March 2019 and is
available for free public updates upto
September 2019.
Bytecode
• Bytecode is program code that has been
compiled from source code into low-level code designed for
a software interpreter.
• It may be executed by a virtual machine (such as a JVM) or
further compiled into machine code, which is recognized by
the processor.
• It is possible to write bytecode directly, but difficult than
writing code in a high-level language.
• Java bytecode is contained in a binary file with a .CLASS
files and are generated from source code using a compiler,
like javac.
• Bytecode is similar to assembly language. Both may be
considered "intermediate languages" i.e. between source
code and machine code.
• The primary difference between the two is that bytecode is
generated for a virtual machine (software), while assembly
language is created for a CPU (hardware).
The bytecode format
• Bytecodes are the machine language of the Java virtual
machine.
• When a JVM loads a class file, it gets one stream of
bytecodes for each method in the class.
• The bytecode stream for a method is executed by
interpreter when that method is invoked during the
course of running the program.
• The Java interpreter is actually a part of JVM.
• A method's bytecode stream is a sequence of
instructions for the Java virtual machine. Each
instruction consists of a one- byte opcode followed by
zero or more operands.
• The opcode indicates the action to take.
• The set of instructions for the JVM may differ from
system to system but all can interpret the bytecode.
C++ vs Java
C++ Java
platform-dependent. platform-independent.
supports multiple doesn't support multiple
inheritance. inheritance through class.
supports operator doesn't support operator
overloading. overloading.
supports pointers. supports pointer internally.
Pointer program in Pointer program in java can
C++ can be written. not be written.
C++ vs Java
C++ Java
supports both call supports call by value only.
by value and call by There is no call by reference in
reference. java.
doesn't have built-in has built-in thread support.
support for threads.
supports virtual has no virtual keyword. We can
keyword so that we override all non-static methods
can decide whether by default. In other words, non-
or not override a static methods are virtual by
function. default.
C++ vs Java
C++ Java
an object-oriented also an object-oriented language.
language. However, However, everything (except
in C language, single fundamental types) is an object in Java.
root hierarchy is not It is a single root hierarchy as everything
possible. gets derived from java.lang.Object.
doesn't support supports documentation comment
documentation (/** ... */) for java source code.
comment.
program memory JVM manages memory through a
managed by the process called garbage collection, which
programmer continuously identifies and eliminates
unused memory in Java programs.
C++ vs Java
C++ Java
support header files uses the import keyword to
include different classes and
methods
support default doesn't support default
arguments arguments
supports structures doesn't support structures and
and unions. unions.
JDK, JRE and JVM
Identifier in Java
Def: A Java identifier is a name given to a package, class,
interface, method, or variable.
• Identifiers must be composed of letters (a-z), (A-Z),
numbers (0-9), the underscore (_) and the dollar sign ($).
• Identifiers may only begin with a letter, the underscore or a
dollar sign

class Test {
public static void main(String [] args) {
int x = 10;
}
}
• No. of idenfiers: 5 i.e. Test (class name), main (function
name), String (pre defined java class), args (array name), x
(variable name)
Some Important Features of Java
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Data Types in Java
• Primitive data types: Primitive datatypes are
predefined by the language and named by a keyword
– There are 8 primitive data types: boolean, char, byte,
short, int, long, float, double.
– boolean (1 bit), byte (1 byte), char (2 bytes),
short (2 bytes), int (4 bytes), long (8 bytes),
float (4 bytes), double (8 bytes)
– char data type in Java is 2 bytes because it uses UNICODE
character set
Unicode is a 16-bit character encoding standard and is
capable to represent almost every character of well-known
languages of the world.
• Non-primitive data types: The non-primitive data
types include Classes, Interfaces, and Arrays.
Data Type

Primitive Non-primitive
String
Boolean Numeric
Array
Character integral etc.

integer Floating-point

boolean char byte short int long float double


(1 bit) (2) (1) (2) (4) (8) (4) (8)
Types of Variable: Division 1
• Primitive variable
– Represented by primitive value
– e.g. int x = 10;
• Reference variable
– Represent reference of an object
– e.g. Student s = new Student()
Types of Variable: Division 2
• local variable
– declared inside the body of the method
– exists only within that method
– cannot be defined with "static" keyword
• instance variable
– declared inside the class but outside the body of the
method
– its value is instance specific and is not shared among
instances
• static variable
– It cannot be local
– a single copy of static variable can be created, which is
shared among all the instances of the class
– Memory allocation for static variable happens only once
when the class is loaded in the memory
Example - variables
class A{
int data = 50; //instance variable
static int m = 100; //static variable
void method(){
int n = 90; //local variable
}
} //end of class
Add two numbers
class Simple{
public static void main(String[] args){
int a = 10;
int b = 12;
int c = a + b;
System.out.println(c);
}
}
Operators in java
Type Operator Associativity
Unary postfix ++ -- Right to Left
Unary prefix ++ -- + - ~ ! (type) Right to Left
Multiplicative / * % Left to Right
Additive + - Left to Right
Shift << >> >>> Left to Right
Relational < <= > >= instanceof Left to Right
Equality == !== Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR | Left to Right
Operators in java - continued

Type Operator Associativity


Logical AND && Right to Left
Logical OR || Right to Left

Ternary ?: Left to Right

Assignment = += -= *= /= %= Left to Right


&= |= <<= >>= >>>=
public class OperatorShifting {
public static void main(String args[]) {
byte x, y;
X = 10;
Y = - 10;
System.out.println("Bitwise Left Shift: x<<2 = "+(x<<2));
System.out.println("Bitwise Right Shift: x>>2 = "+(x>>2));
System.out.println("Bitwise Zero Fill Right Shift: x>>>2 = "+(x>>>2));
System.out.println("Bitwise Zero Fill Right Shift: y>>>2 = "+(y>>>2));
}
}
• Output:
Bitwise Left Shift: x<<2 = 40
Bitwise Right Shift: x>>2 = 2
Bitwise Zero Fill Right Shift: x>>>2 = 2
Bitwise Zero Fill Right Shift: y>>>2 = 1073741821
Standard input-output
• Java Output: to send output to standard output
(screen)
– System.out.println(),
– System.out.print()
– System.out.printf()
 print() - prints string inside the quotes.
 println() - prints string inside the quotes & the
cursor moves to the beginning of the next line.
 printf() - it provides string formatting (similar
to printf in C/C++ programming)
Java Output
class Output {
public static void main(String[] args) {
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
Output:
1. println
2. println
1. Print 2. print
public class Test {
public int age;
public static int credits;
public Test(int a) {
age = a; }
public void setage(int newage) {
age = newage; }
public static void main(String args[]) {
Test obj = new Test(20);
obj.credits = 8;
System.out.println("Age: " + obj.age:+ " Credits: " + obj.credits);
obj.setage(25);
System.out.println("Age: " + obj.age:+ " Credits: " + obj.credits);
} Output:
Age = 20 Credits = 8
}
Age = 25 Credits = 8
input from console
• Using Buffered Reader Class
– Java classical method to take input, Introduced in JDK1.0.
– connects to input stream of keyboard
– converts the byte-oriented stream into character-oriented
stream
• Using Scanner Class
– the most preferred method to take input
– Scanner class in Java is in the java.util package.
– Convenient methods for parsing primitives (nextInt(),
nextFloat(), …)
• Using Console Class
import java.util.Scanner;
public class AreaCircle {
public static void main(String[] args)
{
double pi = 3.14, area;
Scanner s = new Scanner(System.in);
System.out.print("Enter radius of circle: ");
int r = s.nextInt();
area = pi * r * r;
System.out.println("Area of circle: ” + area);
}
} Enter radius of circle: 4
Area of circle: 50.24
Control Statements
• Selection Statements
– The if statements
– The if-else statements
– The if-else-if statements
– The switch statements
• Iteration Statements
– The while loop
– The for loop
– The do-while loop
– The for-each loop
• Jump Statements
– break statement
– continue statement
– return statement
// Program to check Leap Year
public class LeapYearExample {
public static void main(String[] args) {
int year = 2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Output:
LEAP Year
Switch Statement
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
//Java do-while Loop

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
//with label inside an inner loop to break outer loop
public class BreakExample3 {
public static void main(String[] args) {
aa:
for(int i=1; i<=3; i++){
bb:
for(int j=1; j<=3; j++){
if(i ==2 && j==2){
break aa; //using break statement with label
}
System.out.println(i+" "+j);
}
}
} }
Output:
1 1
1 2
1 3
2 1
for each loop (enhanced for loop)
• an alternative approach to traverse the array or
collection in Java.
• Advantage
– it eliminates the possibility of bugs
– It makes the code more readable.
• Drawback
– it cannot traverse the elements in reverse order.
• Syntax
for(data_type variable : array | collection){
//body of for-each loop
}
//Example of Java for-each loop
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
int total=0;
for(int i:arr){
total=total+i;
}
System.out.println("Total: "+total);
}
}
• Output:
Total: 83
Arrays in Java
• Array contains elements of a similar data type
• stored in a contiguous memory location
• In Java all arrays are dynamically allocated
• Arrays are objects in Java, we can find their
length using member function length
• The size of an array must be specified by an
int value and not long or short
• The direct superclass of an array type is Object
1-Dim Array
• Declaration of Array
dataType[] varName;
dataType []varName;
dataType varName[];
• Constructing an Array
arrayName = new dataType[size];
• Construction and declaration combined (Instantiation)
dataType[] varName = new dataType[size];
• Example:
Int[] a = new int[3];
a[0] = 10; a[1] = 20; a[2] = 30;
Int[] a = {10, 20, 30};
String*+ cars = ,“BMW”, “Ford”, “Maruti”-;
• To find class of object array
System.out.println(a.getclass().getName()); // [I
Multidimensional Array
• Declaration of Array
Int[ ][ ] x;
Int [ ][ ]x;
Int x[ ] [];
• Instantiate Multidimensional Array
int[][] arr = new int[2][3];
Int[ ][ ] x = {{10, 20, 30}, {40, 50, 60}};
• Jagged Array (ragged array) in Java
– an array of arrays with different number of columns
Int[ ][ ] x = new int [2][ ];
X[0] = new int[2];
X[1] = newint[3];
/Java Program to illustrate the jagged array
class Test {
public static void main(String[] args){
int a[][] = new int[2][]; //declaring a 2D array with odd columns

a[0] = new int[3];


a[1] = new int[4];
int count = 0;
for (int i = 0; i < a.length; i++) // a.length is number of rows
for(int j = 0; j < a[i].length; j++)
a[i][j] = count++;
for (int i = 0; i < a.length; i++){
for (int j = 0; j < a[i].length; j++){
System.out.print(a[i][j]+" ");
}
System.out.println(); //new line
} Output:
} //main 0 1 2
} //class Test 3 4 5 6
import java.util.Scanner ;
public class marray {
public static void main ( String args []) {
Scanner s = new Scanner(System.in);
System.out.println("Enter n: ");
int n = s.nextInt();
int [][] data = new int[n][n +2];
System.out.println(“rows = " + data.length + " & columns = " + data [0].length );
for ( int i=0 ; i< data.length; i ++){
for ( int j =0; j < data[0].length; j ++)
data [i][j] = 1; }
int [][][] datam = new int [n][n +2][ n +4];
System.out.println("Dimension: " + datam.length+", "+datam[0].length+",
"+datam[0][0].length);
for ( int i=0 ; i< datam . length ; i ++){
for ( int j =0; j < datam [0]. length ; j ++) Enter n: 5
for ( int k =0; k< datam [0][0]. length ; k ++) rows = 5 & columns = 7
datam [i][j][k] = 1; } } } Dimension: 5, 7, 9
// Program for String manipulation i.e. removing all blanks
import java.util.Scanner ;
public class string_maniuplation {
public static void main ( String args [])
{
Scanner s = new Scanner ( System .in );
System.out.println("Enter String: ");
String line = s. nextLine ();
String newline = "";
for ( int i =0; i< line . length (); i ++) {
if ( line . charAt (i )!= ' ')
newline = newline + line . substring (i, i +1);
}
System . out . println (“String after removing all spaces: ”+ newline );
}
} Enter String: DTU is in Delhi
String after removing all spaces : DTUisinDelhi
Class name of Java array
Array Type Corresponding class name
int [] [I
int[][] [[I
int[][][] [[[I
double[] [D
short[] [S
byte[] [B
boolean [Z
//Java Program to multiply two matrices
public class MatrixMultiplication {
public static void main(String args[]) {
int a[][] = {{1, 1, 1}, {2, 2, 2}};
int b[][] = {{1, 1, 1},{2, 2, 2},{3, 3, 3}};
int c[][]=new int[2][3]; //3 rows and 3 columns
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0; k<3; k++)
{
c[i][j] += a[i][k]*b[k][j];
} //end of k loop
System.out.print(c[i][j]+" ");
}//end of j loop
System.out.println();//new line
} //end of i loop
}}
final keyword in java
• final is a non-access modifier applicable only
to a variable, a method or a class
class Bike{
final int speedlimit = 90; //final variable
void run(){
speedlimit = 400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output: Compile Time Error


length vs length() in Java
• length
– applicable for arrays
– Gives size of the array
– array.length
• length()
– applicable for string objects
– returns the number of characters presents in the string
– string.length()
• The length variable is applicable to array but not for
string objects whereas the length() method is
applicable for string objects but not for arrays.
// length and length()
public class Test {
public static void main(String[] args)
{
int[] array = new int[4];
System.out.println("size of array: " + array.length);
String str = “Java Programming Language"; // str is a string
System.out.println(“size of String: " + str.length());
String*+ str1 = , "Java”, “Programming“, “Language”-;
// str1 is array
System.out.println(str1.length); size of array: 4
} size of String: 25
} 3
Type Casting in Java
• Implicit Conversion i.e. Widening/ Promotion Conversion
– passing a lower size data type like int to a higher size data type
like long. Promotion conformed automatically.
• Explicit Conversion (Narrowing)
– passing a higher size data type like int to a lower size data

Example Implicit conversion:


public class Test {
public static void main(String []args) {
int a = 300;
long b = a;
System.out.println(b);
}
}
Explicit Conversion
public class Test {
public static void main(String []args) {
int a = 300;
byte b = (byte)a; //narrowing
System.out.println(b);
}
}
Type casting
Type promotion in Expressions
• Java automatically promotes each byte, short, or char
operand to int when evaluating an expression.
• If one operand is a long, float or double the whole expression
is promoted to long, float or double respectively.
class Test {
public static void main(String args[]) {
byte b = 42; char c = 'a'; short s = 1024; int i = 5000;
float f = 5.67;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println("result = " + result);
}
}
Java Classes and Objects
• Everything in Java is associated with classes and
objects, along with its attributes and methods.
• A class is a group of objects which have common
properties.
• It is a logical entity. It can't be physical.
• An object is an instance of a class.
• An object is a real-world entity
• An object is a runtime entity
//Defining a Student class and object.
class Student{
int id; //field or data member or instance variable
String name;
public static void main(String args[]){
Student s1 = new Student(); //creating an object
System.out.println(s1.id); //accessing member
System.out.println(s1.name);
}
}
• Output:
0
null
// File: TestStudent.java
class Student{
int id;
String name;
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
} 101 Sonoo
} 102 Amit
Constructors
• Rules for creating Java constructor
– Constructor name must be the same as its class
name
– A Constructor must have no explicit return type
– A Java constructor cannot be abstract, static, final,
and synchronized
• Types of Java constructors
– Default constructor (no-arg constructor)
– Parameterized constructor
//default constructor
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
• Output
0 null
0 null
//Parameterized Constructor File: Student4.java
class Student4{
int id;
String name;
Student4(int i, String n){ //parameterized constructor
id = i;
name = n;
}
//method to display the values
void display() {System.out.println (id + " “ + name);-
public static void main(String args[]) {
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display(); 111 Karan
}
222 Aryan
}
Java Access Modifiers
Access within within outside outside
Modifier class package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Inheritance
• Syntax
class Base-class {
.....
.....
}
class derived-class extends base-class {
.....
.....
}
class Employee{
float salary = 40000;
}
class Programmer extends Employee{
int bonus = 10000;
public static void main(String args[]){
Programmer p = new Programmer();
System.out.println("Programmer salary is: "+p.salary);
System.out.println("Bonus of Programmer is: "+p.bonus);
}
}
• Output:
Programmer salary is: 40000.0
Bonus of Programmer is: 10000
Interface and implements
• An interface is an abstract "class" that is used to group
related methods with "empty" bodies
• The interface keyword is used to declare a special type of
class that only contains abstract methods (empty bodies)
• It cannot be used to create objects
• An interface cannot contain a constructor (as it cannot be
used to create objects)
• To access the interface methods, the interface must be
"implemented" (like inherited) by another class with the
implements keyword (instead of extends).
• The body of the interface method is provided by the
"implement" class
• The implements keyword is used to implement an interface
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Multiple inheritance
• Java does not support "multiple inheritance"
(a class can only inherit from one superclass).
• However, class can implement multiple
interfaces.
• To implement multiple interfaces, separate
them with a comma
// multipleinterfaces
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
Packages in Java
• Package in Java is a group of classes, sub
packages and interfaces.
• A package is a container of a group of related
classes where some of the classes are accessible
are exposed and others are kept for internal
purpose.
• import class from existing packages and use it in
the program e.g. import java.util.Scanner
Here util is a subpackage created in java package
• Packages may be userdefined or in build packages
User-defined packages
• These are the packages that are defined by the user.
• First we create a directory myPackage (name should be
same as the name of the package).
• Then create the MyClass inside the directory with the first
statement being the package names.
• Example
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
• Now we can use the MyClass class in our program using
import myPackage.MyClass

You might also like