Moving+from+C_+to+Java

Published on December 2016 | Categories: Documents | Downloads: 104 | Comments: 0 | Views: 636
of 8
Download PDF   Embed   Report

Comments

Content

Moving from C# to Java
General, including built-in data types and language syntax











In both Java and C# a semicolon must be used to end any single statement
and to separate multiple statements on a line
Both Java and C# have single-line comments that start with //; they also both
have multiple-line comments that start with /* and end with */
o C#’s special documentation comments start with ///; Java’s start with /**
and end with */
Naming conventions are somewhat different in Java and C#:
o Java methods begin with a lower case letter, where C# methods start
with a capital letter (toString vs. ToString, main vs. Main)
o Interfaces in C# usually begin with a capital I (the letter i), like
IComparable, Java’s don’t
o Although both Java and C# class names generally start with a capital
letter, a few built-in C# types start with a lower case letter: in particular
object and string; they must be called Object and String in Java
o In all other cases capitalization is the same in both languages; both use
both Camel case (starts with a lower case letter) and Pascal case (starts
with a capital) in names
Java programs start execution with the public static void main(String[]
args) method, whereas C# programs start with the similar Main() method; in
Java Main() must have a string[] parameter, which is a 0-length array if there
are no arguments passed in to the program when it starts
In both Java and C# variables must be declared to have one specified type, and
they can only be assigned values of that type or of a “compatible” type
o For Java primitive types and C# built-in value types the following
automatic promotions are possible: double  float  long  int 
short  byte and also int  char
 Converting in the other direction requires a cast: int x = (int)
3.14159; // x == 3
o For both Java and C# reference types (objects) a derived or inherited
type can be assigned to a variable of a type of any of its “ancestors”, for
example Object oVar = "abc";
 This includes any interfaces that the reference type implements
o In Java you cannot declare a variable to be of type var, each variable
must have an explicitly-designated type
Java and C# built-in data types:
o As mentioned above, Java’s primitive and C#’s built-in value data types
are the same
 Java does not have the C# struct keyword to create additional
primitive types
o The numeric types are byte, short, int, long, float, and double; a
char represents a single Unicode character, and it is treated as a
number when combined with numeric values
 Java does not have C# types signed sbyte and unsigned ushort,
uint, and ulong
 The arithmetic operators are +, –, *, /, and %, the modulus
operator; when / is used with two integer numeric

Moving from C# to Java

o

values/operands it performs integer division, so
3 / 2 is 1; if either operand is a double, the result is a double, so
3 / 2.0 is 1.5
 Java does not allow you to define (overload) operators so they can
work with other types
Literal char data is surrounded by single quotes: 'a'; there are escape
sequences that work inside these quotes, and common ones are: \n,
\t, \', \", \\

Moving from C# to Java
Both Java and C# have built-in string types, String in Java and string in
C#; double quotes delimit strings, like "abc", and the escape sequences
above also work for strings
 The + operator is overloaded for strings, and “adding”
(concatenating) a string with any other data type first converts
that data type to a string before combining
o Both Java and C# have a bool data type which can only take on the
values true and false
Unlike C#, in Java a source file can only contain one public class, and the
name of the source file must be the same as that class name, eg, public class
MyClass must live in MyClass.java
Both Java and C# use curly braces, { }, to delimit scope of control and where
names are defined; in both languages whitespace like indentation is completely
ignored except inside a char or string
o C# introduces the concept of a namespace, which can appear
anywhere in a source file and can include one or more classes; C#
namespaces are also delimited by curly braces, and can be nested,
unlike Java packages, whose names have to appear only at the top of a
source file following the keyword package, eg, package
com.example.region.mypackage;
Java and C# methods/functions must declare their return types and the types
of their parameters, if any; functions that do not return a value must be
declared as void
o A void function may include one or more return; statements, but is not
required to – such a function returns by default at the end of the function
o A non-void function must include one or more return <<appropriate
value>>; statements, one at every point where the function returns
and at the end of the function if needed
o Unlike C#, Java functions cannot declare optional parameters with
default values
o







Trying Java expressions and statements in Groovy Console




The Mono Project installation comes equipped with an interactive csharp shell
interpreter where you can try C# statements/expressions to see how they work
by following them with a semicolon ;
A similar interpreter / REPL that works pretty well for Java is Groovy Console –
see this website:
http://forgetfulprogrammer.wordpress.com/2013/12/05/groovy-console-pythonlike-repl-for-java/.

Objects and methods


Both Java and C# use standard object-method syntax, where an object (a
literal value, variable name, or expression) is followed by a period and then a
method name with arguments in parentheses:
String s = "hello".toUpperCase()
// in Java, s now refers to
the new string "HELLO"

Moving from C# to Java


Java denotes inheritance by saying extends: class DerivedClass extends
BaseClass { … } – this is used where BaseClass is either an abstract or a
concrete class
o Unlike C#, Java uses a different keyword for implementing interfaces,
implements:
public class ChildClass extends ParentClass implements
Interface1, Interface2, … { … }

Moving from C# to Java
Simple input/output




The Java equivalent to C#’s Console.Write()/WriteLine() is
System.out.print()/println() for output
o Java does not provide curly brace substitution into written strings, like
{0}, etc.
Java also provides a Scanner class to read input and can convert input
Strings to ints or doubles:
import java.util.Scanner; // or java.util.* - at the top of the source
file
// … in main() or some other method
Scanner input = new Scanner(System.in);
String line = input.nextLine();
int x = Integer.parseInt(line); // equivalent to C#’s int.Parse()
function
// also Double.parseDouble(line), Boolean.parseBoolean(line),
etc for all primitive types

Arrays, lists, and dictionaries






Java and C# arrays are declared, initialized, and used in exactly the same way;
Java only provides multidimensional arrays as arrays of arrays: int[][] a =
new int[3][5];
Java provides data structures like C#’s List<T> and Dictionary<TKey,
TValue>, implementations of interfaces List<T> and Map<K,V>, which are
contained in java.util.*. One standard Java List<T> implementation is
ArrayList<T>; a standard Java Map<K,V> implementation is
HashMap<K,V>.
o ArrayList<String> als = new ArrayList<>(); // an ArrayList that
can only contain Strings
 Note: the diamond designator on the right side, <>, is only
in Java 7 and later
 This can also be specified as List<String> als = new
ArrayList<>(); // as interface
o int alss = als.size(); // the number of elements in this list,
initially 0
o HashMap<String, Integer> hmsi = new HashMap<,>(); // a Map
with String keys and Integer values (ints are autoboxed to
Integers, and auto-unboxed as necessary)
 This can also be specified as Map<String, Integer> hmsi =
new HashMap<,>();
o Int hmsis = hmsi.size(); // the number of key-value pairs in this
map, initially 0
Unlike C#, in Java, Lists and Maps cannot be indexed using square brackets
(array index notation)

Moving from C# to Java
Boolean expressions




Java and C# both have all of the standard comparison operators: ==, !=, <=,
>=, <, >; these produce the bool value true or false
o Unlike in C#, in Java == and != do not use the equals method, and only
test for reference equality; if you want to test for content equality,
always use equals. You may have to override equals in your classes to
get this to work; if you do, also override getHashCode!!
Both Java and C# use &&, ||, and ! to combine bool values, and && and ||
short-circuit: if the left-hand operand determines the resulting truth value then
the right operand is not evaluated

Moving from C# to Java
Conditions and decision statements and loops






In both Java and C#, conditions must be written in parentheses, for example:
if (x < 3) {
System.out.println("x is less than 3"); x = x + 1;
}
o Both languages also provide else and use else if to avoid the need for
double indentation
Both Java and C# have a “ternary” operator: int y = (x < 3) ? -1 : +1; // y == -1
if x is less than 3
The Java and C# while, do-while, and for loops work essentially the same way
Java has an “extended” for loop, for (int x : intcollection) { … }; the
corresponding C# loop is the foreach loop, foreach (int x in intcollection) { …
}

String functions and methods
Java vs. C# string Properties and methods
Java
C#
String.length(), eg: "Fred".length() // 4
string.Length, eg: "Fred".Length // also
4
String.toUpperCase(), eg: "Fred".toUpperCase() string.ToUpper(), eg: "Fred".ToUpper() //
// "FRED"
same
String.toLowerCase(), eg: "Fred".toLowerCase()
string.ToLower(), eg: "Fred".ToLower() //
// "fred"
same
String.indexOf(part), eg, "Fred".indexOf("red")
string.IndexOf(part), eg,
// index 1 – returns -1 if part not found
"Fred".IndexOf("red")
// same – returns -1 if part not found
String.startsWith(part), eg,
string.StartsWith(part), eg,
"Fred".startsWith("F")
"Fred".StartsWith("F") // true – also
// true – also string.endsWith(part)
string.EndsWith(part)
String.trim(), eg, " Fred ".trim() // "Fred"
string.Trim(), eg, " Fred ".Trim() // also
"Fred"
String.split("\\s+"), eg, "Hello,
string.Split(), eg, "Hello, world!".Split()
world!".split("\\s+")
// splits on whitespace 
// splits on whitespace 
C# string array: {"Hello,", "world!"}
Java String Array: {"Hello,", "world!"}
String.format("%1$s %2$s %2$s %3$s", "a",
format("{0} {1} {1} {2}", "a", "b", "c")
"b", "c")
or
// produces String "a b b c" using type
"{0} {1} {1} {2}".format("a", "b", "c")
specifier s = String
// same
// other type specifiers are required, like
// however, no type specifiers are
d = int, f = float
required
Accessing libraries
You import libraries in Java, like import java.util.*;, to extend the set of functions,
methods, and classes that are available to your program. In C# you would have used

Moving from C# to Java
a using statement instead: using System;. In Java you can import static variables
and methods from a package by using import static …;.

Sponsor Documents

Recommended

No recommend documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close