Linux 용 JAVA 설치 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 경로를추가해준다 1 2 vi.bash_profile PATH 설정부분에 /usr/java/jdk1.6.0_01/bin/j /jdk160 01/bi 을추가 3..bash_profile ( 환경설정적용 ) 4 만약 javac 가실행이되지않는다면터미널환경설정에서로그인 쉘사용을체크해준다 Java.1
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 screen System.out.println( Java Primer Now Brewing ); 컴파일 : $ javac First.java» First.class 파일생성 실행 : $ java First Java.2
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 i i data types: boolean, char, byte, short, int, long, float, double» reference data types: objects, arrays Java.3
Java 기초 클래스와객체 (Classes and Objects) class Point // constructor to initialize the object public Point(int i, int j) xcoord = i; ycoord = j; public Point() xcoord = 0; ycoord = 0; // exchange the values of xcoord and ycoord public 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 data private int xcoord; //X coordinate private int ycoord; //Y coordinate Java.4
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(); 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.5
Java 기초 Objects as references Object parameters are passed by reference public class Third public static void change(point tmp) tmp.swap(); public static void main(string args[]) //create 2 points and initialize them Point pta = new Point(5, 10); Point ptb = new Point(-15, -25); Point ptd = new Point(0,1); // output their values change(ptd); pta.printit(); ptd.printit(); ptb.printit(); tit() // now exchange values for first point pta.swap(); pta.printit(); //ptc is a reference to ptb; Point ptc = ptb; //exchange the values for ptc ptc.swap(); //output the values ptb.printit(); p ptc.printit(); Java.6
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.7
Java 기초 패키지 (Packages): 관련있는 class 들의모임» core Java application programming interface(api) http://www.javasoft.com 참조 http://java.sun.com/javase/6/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.8
예외처리 (Exception Handling) Public final void wait() throws InterruptedException;» wait() i() 메소드호출이 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 int num=(int)(math.random()*2); try recip=1/num; System.out.println( The reciprocal is +recip); catch(arithmeticexception ti ti e) //output the exception message System.out.println(e); finally System.out.println( The number was +num); Java.9
Inheritance 객체지향언어의특징인이미존재하는 class를확장하여사용하는기능 derived-class extends base-class public Student(String n,int a,string s, 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; 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); s); major=m; GPA=g; public void studentinfo() //call this method in the parent class printperson(); System.out.println( Major: +major); System.out.println( println( GPA: +GPA); public static void main(string args[]) Student stu = new Student("ABC", 20, "123456-1234567", "CSE", 100); stu.studentinfo(); Java.10 private String major; private double GPA;
Class Object (java.lang.object j ) 모든 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.11
Interfaces Interface : class 정의와유사» method 들의구현내용없고 method 들과그파라미터리스트만포함 Polymorphism: 하나이상의형태를가질수있는능력 Polymorphic reference public class Circle implements Shape //initialize the radius of the circle public interface Shape public Circle(double r) radius=r; public double area(); public double circumference(); public static final double PI=3.14159; //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; Java.12 private double radius;
Interfaces public class Rectangle implements Shape public Rectangle(double h,double w) height=h; h; width=w; //calculate the area of a rectangle public double area()return height*width; //calculate l the circumference of a rectangle public double circumference() return 2*(height + width); private double height; private double width; 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); Java.13
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( 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;» protected : 정의된 class 와» public : 정의된 class 밖에서도유효» private : 정의된 class 안에서만유효 유도된 (derived) sub class 에서만유효 Java.14
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; np; public void computeraise() salary+=salary *.05 +numofprograms*25; private int numofprograms; Java.15
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, Java Intern,26000,8); for(int i = 0; i < 3; i++) worker[i].computeraise(); worker[i].printinfo(); Java.16
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 FirstApplet.html 파일 <applet Code = FirstApplet.class Width = 400 Height = 200> </applet> public void paint(graphics g) g.drawstring( Java Primer Now Brewing!,15,15); Java.17
리눅스에서 Applet 실행준비과정 자바 plugin 설치하기» 모질라의플러그인디렉토리로이동하여심볼릭링크를만들여주면자바엣플릿을실행할수있다.» 플러그인디렉토리로이동 # cd /usr/lib/mozilla/plugins/ / / /p /» 심볼릭링크를만든다.» 설치버전에따라 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 /j /j _ 01/jre/bin / 을추가 Java.18
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 의숙제방에복사해주세요. Java.19