Upload
sharla
View
55
Download
6
Embed Size (px)
DESCRIPTION
Linux 용 JAVA 설치. http://java.sun.com/javase/downloads/index.jsp 에서 JDK 6u1 의 Download 를 선택하여 해당 플랫폼의 JDK 6u1 를 다운받는다 Linux 용 RPM 버전 sh jdk-6u1-linux-i586-rpm.bin rpm –Uvh jdk-6u1-linux-i586-rpm PATH 에 JAVA 경로를 추가해준다 vi .bash_profile PATH 설정부분에 /usr/java/jdk1.6.0_01/bin 을 추가 - PowerPoint PPT Presentation
Citation preview
인천대학교 컴퓨터공학과 성미영 Java.1운영체제
1. http://java.sun.com/javase/downloads/index.jsp 에서 JDK 6u1 의 Download
를 선택하여 해당 플랫폼의 JDK 6u1 를 다운받는다
2. Linux 용 RPM 버전
1) sh jdk-6u1-linux-i586-rpm.bin
2) rpm –Uvh jdk-6u1-linux-i586-rpm
3) PATH 에 JAVA 경로를 추가해준다
① vi .bash_profile
② PATH 설정부분에 /usr/java/jdk1.6.0_01/bin 을 추가
③ . .bash_profile ( 환경설정 적용 )
④ 만약 javac 가 실행이 되지 않는다면 터미널 환경설정에서 로그인
쉘사용을 체크해준다
http://www.javasoft.com 참조
http://docs.oracle.com/javase/7/docs/api/index.html 참조
Linux 용 JAVA 설치
인천대학교 컴퓨터공학과 성미영 Java.2운영체제
Java 기초
• Java program: main() 메소드 가지는 class 를 포함하는 하나 이상의 class 들의 모임
» public static void main(String args[])
• 간단한 프로그램» 파일 First.java (main 메소드 가지는 class 이름과 같아야 함 )/* The first simple program*/public class First{
public static void main(String args[]) {//output a message to the screenSystem.out.println(“Java Primer Now Brewing”);
}}
• 컴파일 : $ javac First.java» First.class 파일 생성
• 실행 : $ java First
인천대학교 컴퓨터공학과 성미영 Java.3운영체제
Java 기초
• 메소드 (Methods)public class Second{
public static void printIt(String message) {System.out.println(message);
}public static void main(String args[]) {
printIt(“Java Primer Now Brewing”);}
}• 연산자 (Operators)
» 산술 연산자 : + - * / ++(autoincrement) --(autodecrement)» 관계 연산자 : ==(equality) !=(inequality) &&(and) ||(or)» 문자열 연산자 : +(concatenate)
• 문장 (Statements): C 언어와 유사» for 문» while 문» if 문
• 데이터 형» primitive data types: boolean, char, byte, short, int, long, float,
double» reference data types: objects, arrays
인천대학교 컴퓨터공학과 성미영 Java.4운영체제
Java 기초
• 클래스와 객체 (Classes and Objects)class Point{
// constructor to initialize the objectpublic Point(int i, int j) {
xCoord = i;yCoord = j;
}public Point() {
xCoord = 0;yCoord = 0;
}// exchange the values of xCoord and yCoordpublic void swap() {
int temp;temp = xCoord;xCoord = yCoord;yCoord = temp;
}public void printIt() {
System.out.println(“X coordinate = “ + xCoord);System.out.println(“Y coordinate = “ + yCoord);
}// class dataprivate int xCoord; //X coordinateprivate int yCoord; //Y coordinate
}
인천대학교 컴퓨터공학과 성미영 Java.5운영체제
Java 기초
• 클래스 Point 타입의 객체 ptA 생성» constructor Point
• 클래스 이름과 동일해야 함• no return value
» ( 예 ) Point ptA = new Point(0, 15);• method overloading: 한 클래스 안에 이름이 같은 두개의 메소드 공존 ( 단
, 파라미터 리스트의 데이터 타입은 달라야 함 )» ( 예 ) Point ptA = new Point();
• static method 와 instance method» static: 객체와 연결 없이 단지 메소드 이름만으로 호출
• class Second 의 printIt();» instance: 반드시 객체의 특정 instance 와 연결하여 호출
• ptA.swap();• ptA.printIt();
• public 과 private» public: class 외부에서 접근 가능
• constant 는 키워드 static final 로 정의• public static final double PI = 3.14159;
» private: class 내부에서만 접근 가능• By reference
» instance 생성마다 reference( 포인터 개념 ) 설정됨» 메소드의 모든 파라미터들은 reference 로 전달됨» 키워드 this: 자기 자신을 참조 하는 객체 (self-referential object)
제공
인천대학교 컴퓨터공학과 성미영 Java.6운영체제
Java 기초
• Objects as referencespublic class Third{
public static void main(String args[]) {//create 2 points and initialize
themPoint ptA = new Point(5, 10);Point ptB = new Point(-15, -
25);// output their valuesptA.printIt();ptB.printIt();// now exchange values for
first pointptA.swap();ptA.printIt();//ptC is a reference to ptB;Point ptC = ptB;//exchange the values for ptCptC.swap();//output the valuesptB.printIt();ptC.printIt();
}}
• Object parameters are passed by reference
public static void change(Point tmp) {
tmp.swap();
}
…
Point ptD = new Point(0,1);
change(ptD);
ptD.printIt();
…
인천대학교 컴퓨터공학과 성미영 Java.7운영체제
Java 기초
• 배열 (Arrays)» 10 바이트 배열
byte[] numbers = new byte[10];» 배열의 초기화
int[] primeNums = {3,4,7,11,13};» 객체배열 생성 : new 문으로 배열 할당한 후 각 객체를 다시 new 로
할당• 5 references 생성
Point[] pts = new Point[5];• 각 reference 에 해당 객체를 배정
for (int i = 0; I < 5; I++) {pts[i] = new Point(i,i);pts[i].printIt();
}
• Java 의 default initialization» primitive numeric data: zero» arrays of objects: null
인천대학교 컴퓨터공학과 성미영 Java.8운영체제
Java 기초
• 패키지 (Packages): 관련 있는 class 들의 모임» core Java application programming interface(API)
• http://www.javasoft.com 참조• http://docs.oracle.com/javase/7/docs/api/index.html 참조
• core java package 이름 : java.<package name>.<class name>
• 표준 패키지 java.lang» java.lang.String, java.lang.Thread 포함» class 이름만으로 참조 가능
• 다른 패키지들은 full name 으로 참조java.util.Vector items = new java.util.Vector();» 또는import java.util.Vector;Vector items = new Vector();» 또는import java.util.*;
인천대학교 컴퓨터공학과 성미영 Java.9운영체제
예외 처리 (Exception Handling)
• Public final void wait() throws InterruptedException;
» wait() 메소드 호출이 InterruptedException 을 초래할 수 있음
• try-catch 블록으로 예외 처리
try {
//call some method(s) that
//may result in an exception.
}
catch(theException e){
//now handle the exception
}
finally{
//perform this whether the
//exception occurred or not.
}
public class TestExcept{ public static void main(String args[]){ int num,recip;//generate a random number 0 or 1//random() returns a double,type-cast to intnum=(int)(Math.random()*2);try{ recip=1/num; System.out.println(“The reciprocal is ”
+recip);}catch(ArithmeticException e){//output the exception messageSystem.out.println(e);}finally{ System.out.println(“The number was ”+num); } }}
인천대학교 컴퓨터공학과 성미영 Java.10운영체제
Inheritance
public class Student extends Person{ public Student(String n,int a,String s, String m,double g){ //call the constructor in the //parent (Person) class super(n,a,s); major=m; GPA=g; } public void studentInfo(){ //call this method in the parent class printPerson(); System.out.println(“Major: “+major); System.out.println(“GPA: “+GPA); } public static void main(String args[]) { Student stu = new Student("ABC", 20, "123456-1234567", "CSE",
100); stu.studentInfo(); } private String major; private double GPA;}
• 객체지향 언어의 특징인 이미 존재하는 class 를 확장하여 사용하는 기능
• derived-class extends base-class
public class Person{ public Person(String n,int a,String s){ name=n; age=a; ssn=s;}public void printPerson(){ System.out.println(“Name: “ + name); System.out.println(“Age: “+age); System.out.println(“Social Security:
“+ssn);} private String name; private int age; private String ssn;}
인천대학교 컴퓨터공학과 성미영 Java.11운영체제
Class Object (java.lang.Object )
• 모든 class 는 Object 에서 유도되었음• Public class Object
» Constructor : public Object() » Method Summary
• protected Object clone() : Creates and returns a copy of this object.
• boolean equals(Object obj) :Indicates whether some other object is "equal to" this one.
• protected void finalize() : Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
• Class getClass() : Returns the runtime class of an object.• int hashCode() : Returns a hash code value for the object.• void notify() : Wakes up a single thread that is waiting on this
object's monitor.• void notifyAll() : Wakes up all threads that are waiting on this
object's monitor.• String toString() : Returns a string representation of the object.• void wait() : Causes current thread to wait until another thread
invokes the notify() method or the notifyAll() method for this object.
• void wait(long timeout) : Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
• void wait(long timeout, int nanos) : Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
인천대학교 컴퓨터공학과 성미영 Java.12운영체제
Interfaces
• Interface : class 정의와 유사» method 들의 구현 내용 없고 method 들과 그 파라미터 리스트만 포함
• Polymorphism: 하나 이상의 형태를 가질 수 있는 능력• Polymorphic reference
public interface Shape{ public double area(); public double circumference(); public static final double PI=3.14159;}
public class Circle implements Shape
{
//initialize the radius of the circle
public Circle(double r){
radius=r;
}
//calculate the area of a circle
public double area(){
return PI*radius*radius;
}
//calculate the circumference of a circle
public double circumference(){
return 2*PI*radius;
}
private double radius;
}
인천대학교 컴퓨터공학과 성미영 Java.13운영체제
Interfaces
public class TestShapes
{
public static void display(Shape figure){
System.out.println(“The area is “ + figure.area());
System.out.println(“The circumference is “+ figure.circumference());
}
public static void main(String args[]){
Shape figOne=new Circle(3.5);
display(figOne);
figOne=new Rectangle(3,4);
display(figOne);
}
}
public class Rectangle implements Shape
{
public Rectangle(double h,double w){
height=h;
width=w;
}
//calculate the area of a rectangle
public double area(){return height*width;}
//calculate the circumference of a rectangle
public double circumference()
{ return 2*(height + width); }
private double height;
private double width;
}
인천대학교 컴퓨터공학과 성미영 Java.14운영체제
Abstract Classes
• Shape Interface 의 method 들은 모두 추상적임 (abstract) ( 정의되어 있지
않음 )» 키워드 abstract : optional, implied
• Abstract class: 추상 메소드 (abstract method) 와 보통의 정의된 메소드(defined method) 포함
• Interface 와 abstract class 에서는 instance 만들 수 없음public abstract class Employee{ public Employee(String n,String t,double s){ name=n; title=t; salary=s; } public void printInfo(){ System.out.println(“Name: “+name); System.out.println(“Title: “+title); System.out.println(“Salary : $ “ +salary); } public abstract void computeRaise(); private String name; private String title; protected double salary;}
» public : 정의된 class 밖에서도 유효» private : 정의된 class 안에서만 유효» protected : 정의된 class 와 유도된
(derived) sub class 에서만 유효
인천대학교 컴퓨터공학과 성미영 Java.15운영체제
Abstract Classes
• A manager
public class Manager extends Employee
{ public Manager(String n, String t,
double s) { super(n,t,s);
} Public void computeRaise(){ salary+=salary * .05+BONUS; } private static final double
BONUS=2500;}
• A developer
public class Developer extends Employee
{
public Developer(String n, String t, double s, int np){
super(n,t,s);
numOfPrograms=np;
}
public void computeRaise(){
salary+=salary * .05 +numOfPrograms*25;
}
private int numofPrograms;
}
인천대학교 컴퓨터공학과 성미영 Java.16운영체제
Abstract Classes
• Manager class 와 Developer class 의 사용
public class TestEmployee{
public static void main(String arg[]){
Employee[] worker = new Employee[3];worker[0] = new Manager(“Pat”,”Supervisor”,30000);worker[1] = new Developer(“Tom”,”Java
Tech”,28000,20);worker[2] = new Developer(“Jay”,”Java
Intern”,26000,8);for(int i = 0; i < 3; i++){
worker[i].computeRaise(); worker[i].printInfo();
}}
인천대학교 컴퓨터공학과 성미영 Java.17운영체제
Applet
• standalone application : 지금까지 본 자바 프로그램들• applet : web page 에 삽입되어 실행되는 자바 프로그램
» No main()» Constructor: init()
• AppletViewer FirstApplet.html 로 실행
• FirstApplet.java 파일import java.applet.*;import java.awt.*;
public class FirstApplet extends Applet{ public void init(){ //initialization code goes here }
public void paint(Graphics g){ g.drawString(“Java Primer Now Brewing!”,15,15); }}
• FirstApplet.html 파일<applet
Code = FirstApplet.classWidth = 400Height = 200></applet>
인천대학교 컴퓨터공학과 성미영 Java.18운영체제
리눅스에서 Applet 실행준비 과정
•자바 plugin 설치하기» 모질라의 플러그인 디렉토리로 이동하여 심볼릭 링크를
만들여주면 자바 엣플릿을 실행할수 있다 .
» 플러그인 디렉토리로 이동
# cd /usr/lib/mozilla/plugins/ » 심볼릭 링크를 만든다 . » 설치 버전에 따라 jre 버전 디렉토리가 생기므로 각 버전에 맞는
디렉토리를 확인후 링크한다 .
# ln -s /usr/java/jdk1.6.0_01/jre/plugin/i386/ns7/libjavaplugin_oji.so
PATH 에 JAVA 경로 추가
# vi .bash_profile
PATH 설정 부분에 /usr/java/jdk1.6.0_01/jre/bin 을 추가
인천대학교 컴퓨터공학과 성미영 Java.19운영체제
Java Primer 실습 과제 ( 택 1)
1. java.lang.ArrayIndexOutOfBoundsException 을 테스트 하는 TestArrayException.java 프로그램 작성int [] num = {5, 10, 15, 20, 25};for (int I = 0; I < 6; i++)
System.out.println(num[i]);
2. Vector 인스턴스 생성 후 아래 내용을 담고 있는 객체 3 개 삽입하고 각각의 내용을 출력하는 TestVector.java 프로그램 작성String first=“The first element”;String second=“The second element”;String third=“The third element”;
★ 실습 결과는 Unix 서버 117.16.244.157 과 117.16.244.59 의 숙제방에 복사해 주세요 .