Download presentation
Presentation is loading. Please wait.
1
Introduction to Java Programming
2
First Program public class HelloWorld {
public static void main(String args[]) { System.out.println("Hello World"); }
3
Compiling and Running HelloWorld.java HelloWorld.class
javac HelloWorld.java HelloWorld.java compile source code run HelloWorld.class java HelloWorld bytecode
4
Java Data Types Primitive Data Types: Reference types
boolean true or false char unicode! (16 bits) byte signed 8 bit integer short signed 16 bit integer int signed 32 bit integer long signed 64 bit integer float,double IEEE 754 floating point Reference types Arrays Strings Objects
5
Operators & Control Structures
Assignment: =, +=, -=, *= Numeric: +, -, *, /, %, ++, -- Relational: ==,!=, <, >, <=, >= Boolean: &&, ||, ! Bitwise: &, |, ^, ~, <<, >> class Sample { public static void main(String[] args) { int number = 0; if (number > 0) { System.out.println("Number is positive."); } else { System.out.println("Number is negative."); for(number=0;number<10;number++) System.out.println(number); while(number>0) conditional: if if else switch loop: while for do break and continue
6
Exceptions Terminology:
throw an exception: signal that some condition (possibly an error) has occurred. catch an exception: deal with the error (or whatever). try { // code that can throw an exception } catch (Exception e) { // code to handle other exceptions } finally { // code to run after try or any catch }
7
Classes and Objects All Java statements appear within methods, and all methods are defined within classes. One top level public class per .java file. typically end up with many .java files for a single program. One (at least) has a static public main() method. Class name must match the file name! compiler/interpreter use class names to figure out what file name is.
8
Classes and Objects User-defined data types
Defined using the “class” keyword Each class has associated Data members (any object type) Methods that operate on the data New instances of the class are declared using the “new” keyword “Static” members/methods have only one copy, regardless of how many instances are created
9
Sample Class & Constructor
public class Point { private double x,y; public Point() { x=y=0; } public Point(double x, double y) { this.x = x; this.y=y; public double distanceFromOrigin(){ return Math.sqrt(x*x+y*y);
10
Objects and new You can declare a variable that can hold an object: Point p; but this doesn’t create the object! You have to use new: Point p = new Point(3.1,2.4); Strings are special. You can initialize Strings like this: String blah = "I am a literal "; Using objects object.method() object.field
11
Arrays Arrays are supported as a second kind of reference type (objects are the other reference type). creating an array requires new int x[] = new int[1000]; byte[] buff = new byte[256]; float[][] mvals = new float[10][10]; int[] foo = {1,2,3,4,5}; String[] names = {“Joe”, “Sam”}; Point [] p=new Point[3]; p[0]=new Point(5,2); p[1]=new Point(1,1);
12
Notes on Arrays index starts at 0. arrays can’t shrink or grow.
e.g., use Vector instead. Arrays have a .length int[] values; int total=0; for (int i=0;i<value.length;i++) { total += values[i]; }
13
Reference Types Objects and Arrays are reference types
Primitive types are stored as values. Reference type variables are stored as references (pointers that we can’t mess with). There are significant differences! int x=3; int y=x; Point p = new Point(2.3,4.2); Point t = p;
14
Passing arguments to methods
Primitive types: the method gets a copy of the value. Changes won’t show up in the caller. Reference types: the method gets a copy of the reference, the method accesses the same object! int sum(int x, int y) { x=x+y; return x; } void increment(int[] a) { for (int i=0;i<a.length;i++) a[i]++;
15
Comparing Reference Types
Comparison using == means: “are the references the same?” (do they refer to the same object?) Sometimes you just want to know if two objects/arrays are identical copies. use the .equals() method you need to write this for your own classes!
16
Packages You can organize a bunch of classes and interfaces into a package. defines a namespace that contains all the classes. You need to use some java packages in your programs java.lang java.io java.util import java.io.File
17
Inheritance and Polymorphism
“is-a” relationship Subclass is derived from one existing class (superclass) public class Student { String name; char gender; Date birthday; Vector<Grade> grades; double getGPA() { … } int getAge(Date today) { public class Professor { String name; char gender; Date birthday; Vector<Paper> papers; int getCiteCount() { … } int getAge(Date today) {
18
Inheritance and Polymorphism
public class Person { String name; char gender; Date birthday; int getAge(Date today) { … } public class Student { String name; char gender; Date birthday; Vector<Grade> grades; double getGPA() { … } int getAge(Date today) { public class Professor { String name; char gender; Date birthday; Vector<Paper> papers; int getCiteCount() { … } int getAge(Date today) {
19
Inheritance modifier(s) class ClassName extends ExistingClassName {
memberList } public class Circle extends Shape { . }
20
Inheritance public class Rectangle { public int Height,Width; . . . }
public class Box extends Rectangle { public int Length; . . . }
21
Inheritance Subclasses have all of the data members and methods of the superclass Subclasses can add to the superclass Additional data members Additional methods Subclasses are more specific and have more functionality Superclasses capture generic functionality common across many types of objects
22
Overriding Methods A subclass can override (redefine) the methods of the superclass Objects of the subclass type will use the new method Objects of the superclass type will use the original
23
Overriding Methods public class Rectangle { public int Length,Width;
public double area() return Length * Width; } public class Box extends Rectangle { public int Height; public double area() return 2*(Length*Width+ Length*height +Width*Height); }
24
Final Methods Can declare a method of a class final using the keyword final public final void doSomeThing() { //... } If a method of a class is declared final, it cannot be overridden with a new definition in a derived class Can also declare a class final using the keyword final
25
Calling methods of the superclass
To write a method’s definition of a subclass, specify a call to the public method of the superclass If subclass overrides public method of superclass, specify call to public method of superclass: super.MethodName(parameter list) If subclass does not override public method of superclass, specify call to public method of superclass: MethodName(parameter list)
26
Calling methods of the superclass
class Box public void setDimension(double l, double w, double h) { super.setDimension(l, w); if (h >= 0) height = h; else height = 0; }
27
Defining Constructors of the Subclass
Call to constructor of superclass: Must be first statement Specified by super parameter list public Rectangle() { width=length = 0; } public Rectangle(double l, double w) { width=w; length = l; } public Box() { super(); height = 0; } public Box(double l, double w, double h) super(l, w); height = h;
28
Access Control Access control keywords define which classes can access classes, methods, and members Modifier Class Package Subclass World public Y protected N private
29
Polymorphism Late binding or dynamic binding (run-time binding):
Method to be executed is determined at execution time, not compile time Polymorphism: to assign multiple meanings to the same method name Implemented using late binding
30
Polymorphism Can treat an object of a subclass as an object of its superclass A reference variable of a superclass type can point to an object of its subclass Person p1; PartTimeEmployee p2; p1 = new Person("John", "Blair"); p2 = new PartTimeEmployee("Susan","Johnson",12.50,45); p1 = p2; System.out.println(p1.toString()); Susan Johnson wages are: $562.5
31
Polymorphism and References
Shape myShape = new Circle(); // allowed Shape myShape2 = new Rectangle(); // allowed Rectangle myRectangle = new Shame(); // NOT allowed
32
Polymorphism Operator instanceof: determines whether a reference variable that points to an object is of a particular class type This expression evaluates to true if p points to an object of the class BoxShape; otherwise it evaluates to false: p instanceof BoxShape
33
Abstract Methods A method that has only the heading with no body
Must be implemented in a subclass Must be declared abstract public double abstract area(); public void abstract print(); public abstract object larger(object); void abstract insert(int insertItem);
34
Abstract Classes A class that is declared with the reserved word abstract in its heading An abstract class can contain instance variables, constructors, finalizers, and non-abstract methods An abstract class can contain abstract methods If a class contains an abstract method, the class must be declared abstract You cannot instantiate an object of an abstract class type; can only declare a reference variable of an abstract class type You can instantiate an object of a subclass of an abstract class, but only if the subclass gives the definitions of all the abstract methods of the superclass
35
Abstract Class Example
public abstract class AbstractClassExample { protected int x; public void abstract print(); public void setX(int a) x = a; } public AbstractClassExample() x = 0;
36
Interfaces A class that contains only abstract methods and/or named constants To be able to handle a variety of events, Java allows a class to implement more than one interface
37
Composition One or more members of a class are objects of another class type “has-a” relation between classes For example, “every person has a date of birth”
38
Concurrent Programming
Java is multithreaded! threads are easy to use. Two ways to create new threads: Extend java.lang.Thread Overwrite “run()” method. Implement Runnable interface Include a “run()” method in your class. Starting a thread new MyThread().start(); new Thread(runnable).start();
39
The synchronized Statement
Java is multithreaded! threads are easy to use. Instead of mutex, use synchronized: synchronized ( object ) { // critical code here } You can also declare a method as synchronized: synchronized int blah(String x) { // blah blah blah }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.