Java Concepts: Sunil Gupta
Java Concepts: Sunil Gupta
Sunil Gupta
Java - General
• Java is:
– platform independent programming language
– similar to C++ in syntax
– similar to Smalltalk in mental paradigm
• Pros: also ubiquitous to net
• Cons: interpreted, and still under development
(moving target)
Class Loader
Java Class
Bytecode Libraries
Verifier
Java
Source
(.java)
Runtime System
Hardware
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
How it works…!
int a = 1, b = 2, c = 5
a=b=c
System.out.print(
“a= “ + a + “b= “ + b + “c= “ + c)
• Or, alternatively:
if ( x < 10 ) { x = 10; }
== Equal (careful)
!= Not equal
>= Greater than or equal
<= Less than or equal
> Greater than
< Less than
WRONG! CORRECT!
if( i == j ) {
if( i == j ) if ( j == k )
if ( j == k ) System.out.print(
System.out.print( “i equals k”);
“i equals k”); }
else else
System.out.print( System.out.print(“i is
“i is not equal to not equal to j”); //
j”); Correct!
while(response == 1) {
System.out.print( “ID =” + userID
[n]);
n++;
response = readInt( “Enter “);
}
What is the minimum number of times the loop is executed?
What is the maximum number of times?
do {
System.out.print( “ID =” + userID[n] );
n++;
response = readInt( “Enter ” );
}while (response == 1);
• Encapsulation
– Objects hide their functions
(methods) and data
(instance variables)
• Inheritance
car
Super class
– Each subclass inherits all
variables of its superclass
auto-
• Polymorphism
manual
matic
Subclasses
Class Fruit{
int grams;
int cals_per_gram;
int total_calories() {
return(grams*cals_per_gram);
}
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Methods
• A method is a named sequence of code that can be invoked by other
Java code.
• A method takes some parameters, performs some computations and
then optionally returns a value (or object).
• Methods can be used as part of an expression statement.
• Example:
Open a file "myfile.txt" for reading
FileInputStream fis = new FileInputStream("myfile.txt");
• Once a stream (e.g., file) has been opened, we can attach filters
• Filters make reading/writing more efficient
• Most popular filters:
•
For basic types:
• DataInputStream, DataOutputStream
•
For objects:
• ObjectInputStream, ObjectOutputStream
import java.util.*;
public class ReadDate {
public ReadDate () {
Date d = null;
ObjectInputStream s = null;
try { FileInputStream f = new FileInputStream ("date.ser");
s = new ObjectInputStream (f);
} catch (IOException e) { e.printStackTrace(); }
try { d = (Date)s.readObject (); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
catch (InvalidClassException e) { e.printStackTrace(); }
catch (StreamCorruptedException e) { e.printStackTrace(); }
catch (OptionalDataException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
System.out.println ("Date serialized at: "+ d);
}
public static void main (String args[]) { new ReadDate (); }
}