programming in java lecture-2 java introduction. platform computing platform include hardware and...
TRANSCRIPT
Programming in java
Lecture-2
Java Introduction
PlatformComputing platform include hardware and software framework, this combination allows software to run.
Platform problem
Source code
Compiler(windows)
Object code
Platform problem
Source code
Compiler(windows)
Object code
Compiler(linux)
Compiler(mac)
Source code Source code
Object code
Object code
java
JavaSource code
Compiler
Intermediate code
Phase I
Intermediate code
Interpreter
Object code
execution
Phase II
Byte code
Interpreter(windows)
Object code
Interpreter(linux)
Interpreter(mac)
Byte code
Object code
Object code
Byte code
WindowsOperating system
LinuxOperating system
MacOperating system
JVM JVM JVM
Byte Code Byte Code Byte Code
Byte code
JavaSource code
Compiler
Intermediate code
Phase I
Intermediate code
Interpreter
Object code
execution
Phase II
0 iload_1 1 iload_2 2 iadd 3 istore_3
A=10B=20C=A+B
Java Features Simple
C++Java
Object oriented
Polymorphism
Inheritance
.
.multithreadi
ng
Java’s Features Platform Independent
Java’s Features Pure Object Oriented
Class One{ Public static void main(String arg[]) { System.out.println(“Hello World”); }}
In java everything must be inside class .
Java’s Features Strongly typed
#include<stdio.h>Void main(){ printf(“Value of I”,&i);
}Every variable used in program must be declared.
Java’s Features Secure
Internet
When java bytecode come from network or another machine, in that case before executing that file verifier check first.
Java Features Multithreading
This is demo for checking multithreading concept of
java.
Developed in early c
This is demo for checking multithreading concept of
java.
Spelling checking operation running while used giving input
Developed in early java
Java’s Features Architectural Neutral Distributed Garbage Collection
Garbage collection
Memory
One ob1=new One();Two ob2=new Two();
two class object
one class object
Ob1 Ob2
Ob1=ob2;
Java Package Java package has two parts
JDK( java development Kit) JRE(java runtime environment)
Java version 1.7
Hello program in c
#include<stdio.h>void main(){printf(“hello world”);}
1. For including header files.
2. main function start
3. print on screen hello world
#include<stdio.h>void main(int argc , char * argv[]){printf(“hello world”);}
Java first program Java is pure object oriented programming
language.
Class demo {
}
main funtion(arguments){print statement for hello world}
First Java Program import java.lang.*; Class demo { public static void main(String arg[]) { System.out.println(“Hello World”); } }
For including libraries in java(like include statement in c)
Name of class
To print message on screen(like printf function)
Main method in java. With string type of argument
Commands to run Save file with name of class, which contains
main method javac demo.java
java demo
Creating, Compiling And Running Java Programs
javac
Java compiler
Java byte code
filename.class To compile the program at the command line type "javac filename.java"
To run the interpreter, at the command line type "java filename"
java
Java Interpreter
Type it in with the text editor of your choice
filename.java
(java file)
Java program
Compiling The Smallest Java Program
public class Smallest{ public static void main (String[] args) { }}
Smallest.java
javac
(Java byte code)
10000100000001000 00100100000001001
: :
Smallest.class
Type “javac Smallest.java”
Running The Smallest Java Program
(Java byte code)
10000100000001000 00100100000001001
: :
Smallest.class
java
Type “java Smallest”
(Platform/Operating specific binary
10100111000001000 00100111001111001
: :
A Java program /*Here you describe what your program does.
*/
public class CLASS-NAME {public static void main (String args[]) {
// your program goes here
} // end of main} // end of class
Compiling and Running
In order to run a Java program: First you compile it
that is, you run a program called compiler that checks whether the program follows the Java syntax
if it finds errors, it lists them If there are no errors, it translates the program into Java
bytecode Example: assume you created a program called Hello.java
prompt>javac Hello.java If successful, this creates a file Hello.class which contains the
translation (Java bytecode) of Hello.java
Then you execute it That is, you call the Java Virtual Machine to interpret and
execute the Java bytecode of your program Example:
prompt>java Hello
Hello world program
When learning a new language, the first program people usually write is one that salutes the world :). Here is the Hello world program in Java.
/*
This program prints out “hello world!” and terminates.
*/public class Hello {
public static void main (String args[]) {
System.out.println(“Hello world!”);
} // end of main
} // end of class
Notes
Comments what follows after // on the same line is considered comment Or, what is in between /* this is a comment */
Indentation is for the convenience of the reader; compiler ignores all spaces and new
lines ; the delimiter for the compiler is the semicolon
All instructions end by semicolon
Lower vs. upper case matters!! Void is different than void Main is different that main
Writing to user (output)
System.out.println(variable-name);prints the value of variable <variable-name> to the user
System.out.println(“any message “);prints the message within quotes to the user
System.out.println(“hello” + “world” + a + “plus“ + b);assuming the value of a is 3 and of b is 7, it printshelloworld3plus7
Note: System.out.println() always prints on a new line.
Example
/* This program illustrates the System.out.println command.*/public class Hello {
public static void main (String args[]) {
System.out.println(“This is my first Java program!”);System.out.print(“I like Java.”); System.out.print(“I think Java is cool.”);
} // end of main} // end of class
Exercise: change the print to println above. What is the difference?
Variable declaration
type variable-name;
Meaning: variable <variable-name> will be a variable of type <type>
Where type can be: int //integer double //real number
Example:
int a, b, c;
double x;
int sum;
Example
/* Printing ages.*/public class MyFirstJavaProgram {
public static void main (String args[]) {
int myAge, myFriendAge; /* declare two integer variables */
myAge = 20; myFriendAge = myAge + 1; //one year older System.out.println(“Hello, I am “ +myAge + “years old, and my
friend is “ + myFriendAge + “ years old”);System.out.println(“Goodbye”);
} // end of main} // end of class
If statements
if (condition) {//instructions
}else {
//instructions}//instructions
condition
instructions instructions
True False
instructions
Boolean conditions
..are built using Comparison operators
== equal!= not equal< less than> greater than<= less than or equal>= greater than or equal
Example:
int x, y; //two variables//assume they have some values if (x <= y) {
System.out.println(“x is smaller”);} else {
System.out.println(“x is larger”);}
Java data types
Type Description
byte 8 bit signed integer
short 16 but signed integer
int 32 bit signed integer
long 64 bit signed integer
float 32 bit signed real number
double 64 bit signed real number
char 16 bit Unicode character (ASCII and beyond)
boolean 1 bit true or false value
String A sequence of characters between double quotes ("")
Primitive types
Primitive type Size Minimum Maximum
boolean 1-bit — —
char 16-bit Unicode 0 Unicode 216- 1
byte 8-bit -128 +127
short 16-bit -215 +215-1
int 32-bit -231 +231-1
long 64-bit -263 +263-1
float 32-bit IEEE754 IEEE754
double 64-bit IEEE754 IEEE754
Default values for primitive members
When a primitive type data is a member of a class, it’s guaranteed to get a default value even if you don’t initialize it.
Not true for those local variables!! There will be compile
error if you use it without initialization
Primitive type Default
boolean false
char ‘\u0000’ (null)
byte (byte)0
short (short)0
int 0
long 0L
float 0.0f
double 0.0d
Example
class Hello{
public static void main ( String[] args ) {int x;System.out.println(x);
} }
>javac Hello.javaHello.java:5: variable x might not have been initialized System.out.println(x); ^1 error
Arrays in Java An ordered collection of something,
addressed by integer index Something can be primitive values, objects, or
even other arrays. But all the values in an array must be of the same type.
Only int or char as index long values not allowed as array index
0 based Value indexes for array “a” with length 10 a[0] – a[9];
a.length==10 Note: length is an attribute, not method
Arrays in Java: declaration Declaration
int[] arr; Person[] persons; Also support: int arr[]; Person persons[]; (confusing,
should be avoided) Creation
int[] arr = new int[1024]; int [][] arr = { {1,2,3}, {4,5,6} }; Person[] persons = new Person[50];
Arrays in Java: safety Cannot be accessed outside of its range
ArrayIndexOutOfBoundsException Guaranteed to be initialized
Array of primitive type will be initialized to their default value Zeroes the memory for the array
Array of objects: actually it’s creating an array of references, and each of them is initialized to null.
Arrays in Java:
second kind of reference types in Java
int[] arr = new int [5];arr
int[][] arr = new int [2][5];
arr[0]
arr[1]
arr
Scoping
Scope determines both the visibility and lifetime of the names defined within the scope
Scope is determined by the placement of {}, which is called block.{
int x = 10;//only x available { int y = 20; //both x and y available } //only x available, y out of scope!}
Scoping
Notice, you cannot do the following, although it’s legal in C/C++.
{int x = 10; { int x = 20; }}
Compile errorHello.java:6: x is already defined in main(java.lang.String[]) int x =20; ^1 error
Scope of objects
When you create an object using new, the object hangs around past the end of the scope, although the reference vanishes.
{String s = new String("abc");
}
Reference s vanishes, but the String object still in memory
Solution: Garbage Collector!
Importing library If you need any routines that defined by java
packageimport java.util.*;import java.io.*;
Put at the very beginning of the java file java.lang.* already been imported. Check javadoc for the classes
Static keyword Want to have only one piece of storage for
a data, regardless how many objects are created, or even no objects created
Need a method that isn’t associated with any particular object of this class
static keyword apply to both fields and methods
Can be called directly by class name Example: java.lang.Math
Non-static fields/methods must be called through an instance
main()
class Hello{int num;public static void main(String[] args)
{num = 10;
}}
>javac Hello.javaHello.java:4: non-static variable num cannot be referenced from a static context num = 10; ^1 error
Main() doesn’t belong in a class
Always static Because program need a place to start, before any
object been created. Poor design decision If you need access non-static variable of
class Hello, you need to create object Hello, even if main() is in class Hello!
class Hello{int num;public static void main(String[] args){
Hello h = new Hello();h.num = 10;
}}