Java from a C perspective. Plan



Similar documents
public static void main(string[] args) { System.out.println("hello, world"); } }

Crash Course in Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

INPUT AND OUTPUT STREAMS

Fundamentals of Java Programming

Java Programming Fundamentals

Java Interview Questions and Answers

CS506 Web Design and Development Solved Online Quiz No. 01

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

C++ INTERVIEW QUESTIONS

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Chapter 1 Java Program Design and Development

Lecture J - Exceptions

Building a Multi-Threaded Web Server

Chapter 2 Introduction to Java programming

Introduction to Java

An Overview of Java. overview-1

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Quick Introduction to Java

CS 111 Classes I 1. Software Organization View to this point:

Java Programming Language

Java Crash Course Part I

WRITING DATA TO A BINARY FILE

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Introduction to Object-Oriented Programming

AP Computer Science Java Subset

D06 PROGRAMMING with JAVA

LAB4 Making Classes and Objects

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

java Features Version April 19, 2013 by Thorsten Kracht

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

The Interface Concept

The C Programming Language course syllabus associate level

Contents. 9-1 Copyright (c) N. Afshartous

Moving from CS 61A Scheme to CS 61B Java

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

JAVA - FILES AND I/O

Programmation 2. Introduction à la programmation Java

What is an I/O Stream?

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

CS 106 Introduction to Computer Science I

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

El Dorado Union High School District Educational Services

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

CSC 551: Web Programming. Fall 2001

Part I. Multiple Choice Questions (2 points each):

CS 1302 Ch 19, Binary I/O

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

An Incomplete C++ Primer. University of Wyoming MA 5310

Lecture 5: Java Fundamentals III

Using Files as Input/Output in Java 5.0 Applications

C++FA 5.1 PRACTICE MID-TERM EXAM

Tutorial: Getting Started

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

D06 PROGRAMMING with JAVA

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

J a v a Quiz (Unit 3, Test 0 Practice)

Semantic Analysis: Types and Type Checking

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Web Development and Core Java Lab Manual V th Semester

Object Oriented Software Design II

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Advanced OOP Concepts in Java

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Object Oriented Software Design

Creating a Simple, Multithreaded Chat System with Java

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Java SE 8 Programming

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

C++ Programming Language

VB.NET Programming Fundamentals

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Files and input/output streams

Week 1: Review of Java Programming Basics

C++FA 3.1 OPTIMIZING C++

Java Application Developer Certificate Program Competencies

Tutorial on C Language Programming

Introduction to Java. CS 3: Computer Programming in Java

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Java Classes. GEEN163 Introduction to Computer Programming

Syllabus for CS 134 Java Programming

Transcription:

Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions, exception programming Some fundamental classes that you ll need in the course 1

Objectives and Book Introduce Java to a sufficient level so that it can be used in the course Mark the main differences from C How-to compile and run Not an exhaustive course of Java Not a thorough explanation of object-orientation Book: Java in a Nutshell, available online http://msp-of.de/oreilly/books/javaenterprise/jnut/index.htm Packages and Classes Java source code is organised in classes Every.java file contains at least one class, which has the same name as the file HelloWorld.java will contain the class HelloWorld) Classes are organized in packages, hierarchically. Generally, a package is a directory all.java files of classes from the package mycompany.mypackage will be in the directory mycompany/mypackage, etc. 2

package and import Every.java file can begin with at most one package statement, declaring the package of the class package se.mycompany.mypackage; and a number of import statements import java.lang.*; // redundant import java.util.vector; import java.util.*; if a class has not been imported, you can refer to it in code by the fully qualified name like se.mycompany.mypackage.helloworld Import is the only way to borrow code from other packages, Java has no #include and no preprocessor (no conditional compilation, etc) Class visibility A.java file can contain other classes but only the one that has the same name as the file can be made visible outside the file. For a class to be visible outside the package, it needs to be declared public package se.mycompany.mypackage; public class HelloWorld { class HelloWorldHelper{ The rest of the classes defined in the file can only be used as local helpers for the main class 3

Classes and Members Think of a class as a C struct (Java has no struct or union), that has both variables and methods (called members). No variable or method can be defined outside class bodies Methods are like C functions Members are not visible outside the class if declared private If declared public, members are visible outside the package If no accessibility is specified, members are visible in the package only Typically, member variables are private or packageaccessible, only some methods (no variables!) are made public (encapsulation) The methods are manipulating the member variables to provide services to the world outside the class package se.kth.nada.ingint; import java.util.date; Example public class HelloWorld extends Object { // no need to speficify extends Object private Date now; // member variable public HelloWorld() // constructor {now= new Date(); public void dosomethinguseful() // member method { System.out.println( Hello World, the time is + now.tostring() // can be just now ); public static void main(string[] argv){ HelloWorld hw= new HelloWorld(); hw.dosomethinguseful(); 4

Objects Classes can be instantiated to create objects Object o= new se.kth.nada.ingint.helloworld(); Or: import se.kth.nada.ingint.*; HelloWorld o= new HelloWorld(); Public methods of the objects can be used to ask them to do something o.dosomethinguseful(); Statics There are no global variables but a class can define a variable visible everywhere else e.g. public static int numberofaccesses; this is not recommeded, because anybody can change the variable as they wish To avoid that, declare the variable final (const in C) All variables declared static are allocated only once and can be seen by all objects made from the class Static methods can be defined to express procedures that are specific to the class but do not refer to any object E.g. out is a static public final variable in class java.lang.system 5

Methods Unlike in C, methods have fixed number of arguments, with fixed types (strict type checking) public void dosomethinguseful(string message) { System.out.println(message+now); A method can be declared after being used by another method in the class (forward declaration) Methods that do not return anything must be explicitely declared void Methods can have identical names provided they have different number or type of arguments Variables and data types Variables can be declared as class member variables or as varialbes in methods (anywhere in the method body, not just in the begining as in C) Integer and floating point types are similar to C, but they have the same size on any platform: byte (8), short (16), int (32), long (64), float (32), double (64) h l i d J h 6

References and Garbage Collection Numeric types, boolean and char are the only Java types that do not refer to an object. They are called primitive types, because they are needed to compose objects The rest of the types are just class names and denote references (Java has no pointers) int aprimitive; HelloWorld areference; If a reference is null it refers to no object. Calling a method of or referring to a field of a null reference will produce NullPointerException Objects that are not referenced from anywhere are garbage collected. Java has only new (like C malloc()), no delete or free() Before the object is forgotten the finalize() method is called protected void finalize() { System.out.println( Help, I m dying!!!! ); Garbage Collection examples When a reference is made null HelloWorld hw= new HelloWorld(); hw.dosomethinguseful(); hw=null; When a method referring to the object ends void mymethod(){ HelloWorld hw= new HelloWorld(); hw.dosomethinguseful(); hw was only known here and has not been passed to other objects When the (only) referrer object is garbage collected Class MyClass{ HelloWorld hw;... Object mc= new MyClass(); when mc dies, hw will die, unless mc passes the hw reference to some other object 7

Arrays You can allocate arrays of variable size, of both primitive types and references to objects All arrays are homogeneous (contain only one type) int [] aprimitivearray= new int[anexpression]; Object [] areferencearray= new HelloWorld[someExpr]; For arrays of references, the objects themselves are _not_ instantiated areferencearray[7]= new HelloWorld() Arrays have a special field called length areferencearray.length==someexpr -> true Refering to a non-existing index throws ArrayIndexOutOfBondsException areferencearray[-1] -> exception Multidimensional arrays can be defined int[][] aprimitivebidimensionalarray matrix= new int[2][7]; // members are arrays that need be // initialized!!! Statements and Operators Following C statements are present in Java with the same meaning: if/else, case/switch/default/break do/while/for/continue/break return return cannot return a value in void methods (some flavours of C allow this) Most operators look the same as in C ==, >=, <=,!=, &&,, &,, ^,etc 8

The main() method Is the entry point in a Java program public static void main(string[] argv) public because it needs to be visible from outside static because at the begining of the program there are no objects created, so we need a method that can be accessed without having an object void, to return a value to the operating system, use System.exit(value) String[] argv (or any other name) is the list of arguments from the command line. Unlike in C, there is no need for an int argument that specifies the number of arguments, because that can be found out argv.length Exceptions When things go wrong java throws exceptions instead of (e.g.) returning a negative value This is much more meaningful for the programmer java.lang.arrayindexoutofbondsexception, java.lang.nullpointerexception, java.io.filenotfoundexception, java.net.unknownhostexception How to throw an exception public void dosthuseful(string msg) throws MyException{ if(msg.length()<3) throw new MyException( Message too short ); 9

Exceptions How to catch an exception public void dosthelse(string msg) { try{ dosomethinguseful(msg); catch(myexception me){ me.printstacktrace(); finally{ // this is executed anyway! RuntimeExceptions do not need to be caught! They are typically programmer errors, so the errors need to be corrected instead java.lang.throwable, java.lang.exception, java.lang.error Letting an exception pass through, so the code that calls the method will need to deal with it public void dosthelse(string msg) throws MyException{ dosomethinguseful(msg); Other issues Other object oriented concepts abstract methods: empty methods to be implemented by subclasses. Classes that have abstract methods must be declared abstract interfaces are like classes but contain only public abstract non-static methods and static public fields. A class can extends at most one class and implements more interfaces protected members are visible in subclasses and in the package (less than public access, more than private) Threads: parallel execution of code: java.lang.thread, java.lang.runnable class DoInParallel implements Runnable{ public void run(){ // code to run in parallel // in other code: new Thread(new DoInParrallel()).start(); 10

Some Fundamental Classes http://java.sun.com/j2se/1.4.2/docs/api/overview-summary.html string manipulation: java.lang: String, StringBuffer containers and iterators: java.util: Vector, Hashtable, Enumeration I/O: java.io: InputStream, OutputStream, Reader, Writer, FileInputStream, FileOutputStream, FileReader, FileWriter 11