Date post: | 04-Apr-2018 |
Category: |
Documents |
Upload: | palash-debnath |
View: | 222 times |
Download: | 0 times |
of 29
7/30/2019 CSE 201 Java Lecture 2 Tc
1/29
CSE 201
Object Oriented Programming Language
Java: Basics
7/30/2019 CSE 201 Java Lecture 2 Tc
2/29
Notes on Packages
` Java classes are arranged in a hierarchy or packagestructure` We can place our classes into packages, but it isoptional`
When we do not specify any package for our class,
the class is placed in a default unnamed package` To place a class in a package we use thepackagestatement
` A class without any access modifier has packagescope only` A public class from a package can be used acrosspackages (i.e., can be used from a class of anotherpackage => the key is import declaration)
7/30/2019 CSE 201 Java Lecture 2 Tc
3/29
Notes on Packages (Contd.)
` Classes in the same package are implicitlyimported into the source code files of otherclasses in the same package
` Thus, an import declaration is not required whenone class in a package uses another in the samepackage
7/30/2019 CSE 201 Java Lecture 2 Tc
4/29
An Example/* /*
Filename: A.java Filename: JavaTest.java
*/ */
package my_package; import my_package.A;
public class A{ public class JavaTest{
private int a; public static void main(String[] args){
public A(int a){ A a = new A(10);
this.a = a; System.out.println(a.getA());
} }
public void setA(int a){ }
this.a = a;
}
public int getA(){return this.a;
}
}
7/30/2019 CSE 201 Java Lecture 2 Tc
5/29
Examining the Example
`The declaration package my_package; in A.java putsthe classes in this file into the package named
my_package
` Class A is made public so it is accessible from outside thepackage my_package` No package declaration at the top of JavaTest.java =>class JavaTest is put under default unnamed package
` The import declaration import my_package.A; inJavaTest.java indicates that class A from my_package willbe used in this file => if this declaration is missing thenCompilation error at A a = new A(10);
` Then why no import for System class ??
7/30/2019 CSE 201 Java Lecture 2 Tc
6/29
Why no import is required for System class` Because System resides in the packagejava.lang, which is automatically importedto every Java application.
`So, we can use all classes from java.lang inour program without explicitly using theimport statement.
7/30/2019 CSE 201 Java Lecture 2 Tc
7/29
More on import
`The use of import is similar to the use ofusing namespace in C++.
` To import all the classes from a package (e.g.java.util) we have to use import java.util.*;
`
Then what will we write to import all classes
from my_package??
7/30/2019 CSE 201 Java Lecture 2 Tc
8/29
Taking input: A Sample Program(InputTest.java)
import java.util.Scanner;
public class InputTest{
public static void main(String args[ ]){
Scanner input = new Scanner(System.in);System.out.print(Enter an integer: );int num1 = input.nextInt();System.out.printf(You entered: %d\n, num1);
// No need to use delete or free type of things.// Java manages memory allocation/deallocation automatically.
} // end method main} // end class InputTest
7/30/2019 CSE 201 Java Lecture 2 Tc
9/29
Examining InputTest.java
`inof System.in is a static member of classSystem. It represents the standard input (similar tostdin or cin)
`Scanner is a class inside the Java API and is locatedin the java.util package`Scanner contains some useful methods to read
different types of data from the standard input (e.g.the keyboard)
`
We have to use the import statement to tell thecompiler that we will use Scanner from java.utilin our program. Otherwisejavac will not recognizeScanner
7/30/2019 CSE 201 Java Lecture 2 Tc
10/29
Examining InputTest.java (Contd.)
` We use a Scanner object to wrap the standardinput object System.in
`We call the method nextInt( ) on the Scannerobject input to read an integer from thekeyboard
` If we enter a non-integer value, an exception isthrown and the program terminates abnormally.Exception Handling is a major topic in Java andwill be discussed elaborately later in the course
7/30/2019 CSE 201 Java Lecture 2 Tc
11/29
Primitive (built-in) Datatypes
7/30/2019 CSE 201 Java Lecture 2 Tc
12/29
Primitive (built-in) Datatypes
` Integers` byte 8 bit integer
` short 16 bit integer
` int 32 bit integer
` long 64 bit integer
` Real Numbers` float 32 bit floating point number
` double 64 bit floating point number
` Others` char 16 bit, Unicode 2.1 character` boolean true or false. false is not zero (0) in Java
7/30/2019 CSE 201 Java Lecture 2 Tc
13/29
Non-Primitive Datatypes
` Non-primitive datatypes` Class Variables
` Array
` Non-primitive types are also called Reference types` Object Example
class Cuboid{private int l, w, h;
public Cuboid(int a, int b, int c){l=a;w=b;h=c;}public static void main(String args[ ]){
Cuboid ob; // ob is a reference pointing to nullob = new Cuboid(10,20,5); // now the actual object is created
}
}
7/30/2019 CSE 201 Java Lecture 2 Tc
14/29
Primitive vs. Non-Primitive Types
Primitive Types
` Can store exactly one value of itsdeclared type at a time. Whenanother value is assigned to thatvariable initial value is replaced
` Primitive type instance variables
are initialized by default
` Instance variables of type byte,short, int, long, float, double and
char initialized to 0` Instance variables of type boolean
initialized to false
` Note: Local variables are notinitialized by default
Reference Types
` Stores locations of objects inmemory and are said to refer toobjects. Objects that arereferenced may contain manyinstance variables and methods
` Reference type instance variables
are by default initialized to null
` Note: Local variables are notinitialized by default
7/30/2019 CSE 201 Java Lecture 2 Tc
15/29
Primitive vs. Non-Primitive Types (Contd.)
Primitive Types
` Primitive type variablesare handled by value -
the actual values arestored in variables andpassed to methods
Reference Types
` All objects and arrays arehandled by reference -
the references are storedin variables and passed tomethods
7/30/2019 CSE 201 Java Lecture 2 Tc
16/29
Java References
` Java references are used to point to Java objectscreated by new
`Java objects are always passed by reference to otherfunctions
` In Java you can never pass an object to anotherfunction by-value` Java references act as pointers but does not allowpointer arithmetic
` We cannot read the value of a reference and hencecannot find the address of a Java object` We cannot take the address of a Java reference
7/30/2019 CSE 201 Java Lecture 2 Tc
17/29
Java References (Contd.)`
`
`
But, we can make a Java reference point to a new object` by copying one reference to another
ClassName ref1 = new ClassName();ClassName ref2 = ref1;
`by creating a new object using new and placing the returnedaddress to the reference in question.
ClassName ref1 = new ClassName(); // first objectref1 = new ClassName(); // another object, address of first object is lost !!!
We cannot place arbitrary values to a reference except the specialvalue null which means that the reference is pointing to nothing.
ClassName ref1 = 100; // compiler errorClassName ref2 = null; // no problem
Trying to use a null reference causes unexpected results orExceptions in many cases
ClassName ref2 = null;ref2.methodName();` Exception in thread "main" java.lang.NullPointerException
7/30/2019 CSE 201 Java Lecture 2 Tc
18/29
Type boolean
` Java boolean type variables cannot be cast toanother datatype
` In Java, 0 and null are not the same as false andnon-zero and non-null are not the same as true
` Both true and false are keywords in Java
` Does not have any relation with int` boolean b = false;` int a = b; // compiler error` int a = (int)b; // compiler error
7/30/2019 CSE 201 Java Lecture 2 Tc
19/29
Operators (Precedence & Associativity)
7/30/2019 CSE 201 Java Lecture 2 Tc
20/29
Operators (Precedence & Associativity)(Contd.)
7/30/2019 CSE 201 Java Lecture 2 Tc
21/29
Operators (Precedence & Associativity)(Contd.)
7/30/2019 CSE 201 Java Lecture 2 Tc
22/29
Using Dialog Boxes
import javax.swing.JOptionPane;
public class NameDialog{
public static void main(String args[ ]){
String name = JOptionPane.showInputDialog(What is your name?);
String message = String.format(Welcome, %s, name);
JOptionPane.showMessageDialog(null, message);
}
}
7/30/2019 CSE 201 Java Lecture 2 Tc
23/29
Executing NameDialog
7/30/2019 CSE 201 Java Lecture 2 Tc
24/29
SumOfInt.java
/*FileName: SumOfInt.java*/
import javax.swing.*;
class SumOfInt
{public static void main(String args[ ]){
String s1=JOptionPane.showInputDialog(null,"Enter 1st number:");String s2=JOptionPane.showInputDialog(null,"Enter 2nd Number:");int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(s2);JOptionPane.showMessageDialog(null,"Sum is : " + (num1+num2));
}
}
7/30/2019 CSE 201 Java Lecture 2 Tc
25/29
Executing SumOfInt
7/30/2019 CSE 201 Java Lecture 2 Tc
26/29
Creating Your First Window(FirstWindow.java)
import java.awt.*;
import javax.swing.*;
public class FirstWindow{
public static void main(String args[]){
JFrame frame = new JFrame("My First Window");
JLabel label1 = new JLabel("I like Java", SwingConstants.CENTER);label1.setFont(new Font("ARIAL", Font.PLAIN, 72));Font fontForButtons = new Font("ARIAL", Font.ITALIC, 24);JButton topButton = new JButton("Click me");topButton.setFont(fontForButtons);JButton bottomButton = new JButton("Click me too");bottomButton.setFont(fontForButtons);
7/30/2019 CSE 201 Java Lecture 2 Tc
27/29
FirstWindow.Java (Contd.)
Container c = frame.getContentPane();c.add(label1);
c.add(topButton, BorderLayout.NORTH);
c.add(bottomButton, BorderLayout.SOUTH);frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
7/30/2019 CSE 201 Java Lecture 2 Tc
28/29
Output of FirstWindow.java
7/30/2019 CSE 201 Java Lecture 2 Tc
29/29
Lecture Content
` Java: How to Program` Chapter 2, 3, 4