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



Similar documents
Introduction to Java

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

Lecture 5: Java Fundamentals III

Java Crash Course Part I

CS 106 Introduction to Computer Science I

1. Writing Simple Classes:

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

Chapter 1 Java Program Design and Development

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

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

An Overview of Java. overview-1

Example of a Java program

Java Programming Fundamentals

Crash Course in Java

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

Object Oriented Software Design

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

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

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

Java Interview Questions and Answers

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

Programmierpraktikum

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Introduction to Object-Oriented Programming

Chapter 2 Introduction to Java programming

Java CPD (I) Frans Coenen Department of Computer Science

Introduction to Java Lecture Notes. Ryan Dougherty

Sample CSE8A midterm Multiple Choice (circle one)

Introduction to Java. CS 3: Computer Programming in Java

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

AP Computer Science Java Subset

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

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

Comp 248 Introduction to Programming

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

Sources: On the Web: Slides will be available on:

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Moving from CS 61A Scheme to CS 61B Java

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

Object Oriented Software Design

Java Basics: Data Types, Variables, and Loops

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

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

Java from a C perspective. Plan

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

CSC 551: Web Programming. Fall 2001

Install Java Development Kit (JDK) 1.8

Basic Java Syntax. Program Structure

Chapter 3. Input and output. 3.1 The System class

Informatica e Sistemi in Tempo Reale

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

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

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

Unit 6. Loop statements

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Statements and Control Flow

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

Pemrograman Dasar. Basic Elements Of Java

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Introduction to Programming

Object-Oriented Programming in Java

Variables, Constants, and Data Types

Computer Programming I

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

Tutorial on C Language Programming

Java with Eclipse: Setup & Getting Started

1001ICT Introduction To Programming Lecture Notes

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Installing Java (Windows) and Writing your First Program

Quick Introduction to Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

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

Programming Languages

Java programming for C/C++ developers

LAB4 Making Classes and Objects

Programming Languages CIS 443

ECE 122. Engineering Problem Solving with Java

C++ INTERVIEW QUESTIONS

Interactive Applications (CLI) and Math

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

VB.NET Programming Fundamentals

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

The C Programming Language course syllabus associate level

Some Scanner Class Methods

Computer Programming Tutorial

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

AP Computer Science Java Mr. Clausen Program 9A, 9B

CS170 Lab 11 Abstract Data Types & Objects

Java Application Developer Certificate Program Competencies

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Building Java Programs

Transcription:

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

Contents Hello World Program Statements Explained Java Program Structure in General Java Classes and Static Methods Data Types, Variables and Constants Java Comments and Documents Control Flow Reading from Keyboard Command Line Arguments Processing Summary and References 2

Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld public static void main(string args[]) System.out.println( Hello World ); 3

Hello World: Java and C S1: S2: S3: S4: S6: // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld public static void main(string args[]) System.out.println( Hello World ); /* helloworld.c: Hello World program */ #define <stdio.h> void main(int argc, char *argv[]) printf( Hello World\n ); 4

Program Processing Compilation # javac HelloWorld.java results in HelloWorld.cla ss Execution # java HelloWorld Hello World 5

Closer Look at - Hello World The class has one method main() public static void main(string args[]) System.out.println( Hello World ); Command line input arguments are passed in the String array args[] e.g java HelloWorld John Jane args[0] John args[1] Jane 6

Closer Look at - Hello World import java.lang.* ; Java allows grouping of related classes into a package. It allows different companies can develop different packages, may even have same class and method names, but they differ by package name: ibm.mathlib.* microsoft.mathlib.* Helps in managing name clash problems. Think of this package as library. import statement somewhat serves similar purpose as C s # include If you don t add import statement, then you need utilise fully qualified name. ibm.mathlib.sin() If you do import ibm.* then you can use mathlib.sin() instead. 7

Java imports java.lang.* by default So, You don t need to import java.lang.* That means, you can invoke services of java s lang package classes/entities, you don t need to use fully qualified names. We used System.out.println() instead of java.lang. System.out.println() 8

public static void main(string args[]) public: The keyword public is an access specifier that declares the main method as unprotected. static: It says this method belongs to the entire class and NOT a part of any objects of class. The main must always be declared static since the interpreter users this before any objects are created. void: The type modifier that states that main does not return any value. 9

System.out.println( Hello World ); java.lang.* All classes/ items in lang package of java package. System is really the java.lang.system class. This class has a public static field called out which is an instance of the java.io.printstream class. So when we write System.out.println(), we are really invoking the println() method of the out field of the java.lang.system class. 10

Java Program Structure Documentation Section Package Statement Import Statements Interface Statements Class Declarations Main Method Class 11

More Java: Classes and static methods // SquareRoot.java: compute square root of number import java.lang.math; class SquareRoot public static void main(string args []) double x = 4; double y; y = Math.sqrt(x); System.out.println("y= "+ y); 12

Basic Data Types Types boolean either true or false char 16 bit Unicode 1.1 byte 8-bit integer (signed) short 16-bit integer (signed) int 32-bit integer (signed) long 64-bit integer (singed) floa t 32-bit floa ting point (IEEE 754-1985) double 64-bit floa ting point (IEEE 754-1985) String (class for manipulating strings) Java uses Unicode to represent characters internally 13

Variables Local Variables are declared within the block of code Variable has a type preceding the name Initial value is set by initialization expressions. type variablename = initialvalue; e.g. int x = 1; Variables can be defined just before their usage (unlike C) e.g., for( int i = 0; i < 10; i+ + ) 14

Constants Constants are similar to variables except that they hold a fixed value. They are also called READ only variables. Constants are declared with the reserved word final. final int MAX_LENGTH = 420; final double PI = 3.1428; By convention upper case letters are used for defining constants. 15

Declaring Constants - example class CircleArea public static void main(string args[]) final double PI = 3.1428; double radius = 5.5; // in cms double area; area = PI * radius * radius; System.out.println("Circle Radius = "+ radius+ " Area= "+ area); 16

Comments English text scattered through the code are comments JAVA supports 3 types of comments /* * / - Usually used from multi-line comments // - Used for single line comments /* * * / - Documentation comments 17

Javadoc Effort to make Java self-documenting True OOP style, encapsulate documentation within code :) Comments beginning with /* * and ending with * / can be extracted and turned into html documentation 18

Control Flow Control Flow Statements in JAVA while loop for loop do-while loop if-else statement switch statement JAVA does not support a goto statement 19

Control Flow - Examples while loop while (squared <= MAX) squared = lo * lo; // Calculate square System.out.println(squared); lo = lo + 1; /* Compute the new lo value */ 20

Control Flow - Examples for loop for (int i = 1; i < MAX; i++) System.out.println(i); // prints 1 2 3 4 5 21

Control Flow - Examples do-while loop do squared = lo * lo; // Calculate square System.out.println(squared); lo = lo + 1; /* Compute the new lo value */ while (squared <= MAX); 22

Control Flow - Examples if-else loop if ( i < 10) System.out.println( i is less than 10 ); else System.out.println( i is greater than or equal to 10 ); 23

Control Flow - Examples switch statement switch (c) case a : System.out.println ( The character is a ); break; case b ; System.out.println ( The character is b ); break; default; System.out.println ( The character is not a or b ); break; 24

Reading from Keyboard As Java does not support a simple APIs for Keyboard Input, we created a class called "Keyboard", which you can use in your program. The Keyboard class facilitates keyboard input by abstracting details about input parsing, conversions, and exception handling. This class reads from standard input (keyboard) and converts the characters into an appropriate type based on the method you call. Some methods you can use are: Keyboard.readString() Keyboard.readWord() Keyboard.readChar() Keyboard.readBoolean() Keyboard.readInt() Keyboard.readLong() Keyboard.readFloat() Keyboard.readDouble() 25

Keyboard class Usage Example Simply copy the Keyboard.java file from: http:// www.cs.mu.oz.au/254/ Keyboard/keyboard.html into your program directory and access its methods as if they are standard methods. The Java complier will link them automatically. An Example Program: // A class to execute one or more Keyboard methods class Test public static void main(string[] args) System.out.print("Please enter a string: "); String str = Keyboard.readString(); System.out.println("String = " + str); System.out.print("Please enter an int number: "); int numint = Keyboard.readInt(); System.out.println("int = " + numint); 26

Command Line Arguments Command line arguments provide one of the ways for supplying input data at the time of execution instead of including them in the program. They are supplied as parameters to the main() method: public static void main(string args[]) args is declared of an array of strings (aka string objects). args[0] is the first parameter, args[1] is the 2 nd argument and so on The number of arguments passed identified by: args.length E.g. count = args.length; Example Invocation and values: java MyProgram hello melbourne args.length will be 2 args[0] will be hello and args[1] will be melborune 27

Printing command line arguments // ComLineTest.java: testing command line arguments class ComLineTest public static void main(string args[]) int count, i = 0; String mystring; count = args.length; System.out.println("Number of Arguments = "+ count); while( i < count ) mystring = args[i]; i = i + 1; System.out.println(i + " : " + "Java is "+ mystring+ "!"); + concatenates strings or numbers 28

Execution Example java ComLineTest Simple Object_Oriented Distributed Robust Secure Portable Multithread Dynamic The output of program will be: Number of Arguments = 8 1 : Java is Simple! 2 : Java is Object_Oriented! 3 : Java is Distributed! 4 : Java is Robust! 5 : Java is Secure! 6 : Java is Portable! 7 : Java is Multithread! 8 : Java is Dynamic! 29

Summary We discussed meaning of statements in hello world program We discussed various basic constructs and syntax. Apart from OO specific items, most keywords or constructs in Java have similar meaning and usage style as C. 30

References Chapter 3: Overview of Java Language Chapters To Browse (if you have forgotten C syntax/ constructs): Chapter 4: Constants, Variables, and Data Types Chapter 5: Operators and Expressions Chapter 6: Decision Making and Branching Chapter 7: Decision Making and Looping 31