0% found this document useful (0 votes)
2 views15 pages

Java TP Syntax

This document serves as a comprehensive Java syntax reference, detailing various constructs organized by topic, including classes, inheritance, abstract classes, exception handling, file I/O, arrays, and collections. Each section provides explanations and code examples to illustrate the concepts. It also includes a quick-reference section summarizing key syntax and their purposes within the repository.

Uploaded by

linaliza2006663
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Java TP Syntax

This document serves as a comprehensive Java syntax reference, detailing various constructs organized by topic, including classes, inheritance, abstract classes, exception handling, file I/O, arrays, and collections. Each section provides explanations and code examples to illustrate the concepts. It also includes a quick-reference section summarizing key syntax and their purposes within the repository.

Uploaded by

linaliza2006663
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Syntax Reference

Based on itsmeisraa/java_tp
School Homework Series – TP2 through TP8

This document collects every Java syntax construct used across the repository, organized by topic. Each
section explains the concept and shows the exact code found in the TPs.
1. Class & Object Basics
The foundation of Java: defining a class with fields, constructors, and methods, then instantiating objects.

1.1 Declaring a Class with Fields


class Point {
private int x; // private field – encapsulated
private int y;

// Constructor
public Point(int x, int y) {
this.x = x; // 'this' refers to the current instance
this.y = y;
}
}

1.2 Instance Methods


public void display() {
[Link]("Point(" + x + ", " + y + ")");
}

public void move(int dx, int dy) {


this.x += dx;
this.y += dy;
}

1.3 Using Math Library


public double calculateDistanceTo(Point other) {
double xDiff = other.x - this.x;
double yDiff = other.y - this.y;
return [Link]([Link](xDiff, 2) + [Link](yDiff, 2));
// ^[Link]() ^[Link]() – static utility methods
}

1.4 Creating and Using Objects (main)


public class main {
public static void main(String[] args) {
Point currentPoint = new Point(5, 7); // instantiation with 'new'
Point targetPoint = new Point(9, 3);

double d = [Link](targetPoint);
[Link]("Distance: " + d); // string concatenation
}
}
2. Inheritance
Java uses extends for single inheritance. The child class inherits all non-private members and can
override methods.

2.1 extends – Basic Inheritance


class Point {
int x;
int y;
public Point(int x, int y) { this.x = x; this.y = y; }
public void Display() {
[Link]("x = " + x);
[Link]("y = " + y);
}
}

class PointCol extends Point { // 'extends' keyword


String col;

public PointCol(int x, int y, String col) {


super(x, y); // call parent constructor with 'super(...)'
[Link] = col;
}

public void coulorise(String col) { [Link] = col; }

@Override // annotation – signals method override


public void Display() {
[Link](); // call parent version with '[Link]()'
[Link]("color = " + col);
}
}

2.2 Inheritance Chain – Vehicle / Car


class Vehicule {
protected String model; // 'protected' – visible to subclasses
int year;

public Vehicule(int year, String model) {


[Link] = year;
[Link] = model;
}
public void DisplayInfo() {
[Link](" model = " + model);
[Link](" year = " + year);
}
}

class Car extends Vehicule {


private int fueleff;

public Car(int fueleff, String model, int year) {


super(year, model); // delegate to Vehicule constructor
[Link] = fueleff;
}

public double calculcons(double distance) {


return (fueleff * distance) / 100;
}

public double getfueleff() { return fueleff; } // getter

@Override
public void DisplayInfo() {
[Link]();
[Link]("Fuel Efficiency: " + fueleff + " L/100km");
}
}

2.3 Polymorphism – parent reference to child object


// A Point reference can hold a PointCol object
Point p1 = new PointCol(3, 4, "red");
Point p4 = new Point(63, 72);
[Link](); // calls [Link]() at runtime (dynamic dispatch)
[Link](); // calls [Link]()
3. Abstract Classes
An abstract class cannot be instantiated and may contain abstract methods that subclasses must
implement.

3.1 Declaring an Abstract Class


abstract class Shape { // 'abstract' keyword on class
public abstract double area(); // abstract method – no body
public abstract double perimeter(); // subclass MUST implement

// concrete method – shared by all shapes


public void display() {
[Link](" shape: area=" + area());
}
}

3.2 Concrete Subclasses


class Circle extends Shape {
double radius;
public Circle(double radius) { [Link] = radius; }

@Override
public double area() { return [Link] * radius * radius; }

@Override
public double perimeter() { return 2 * [Link] * radius; }
}

class Rectangle extends Shape {


double length, width;
public Rectangle(double length, double width) {
[Link] = length; [Link] = width;
}
@Override public double area() { return length * width; }
@Override public double perimeter() { return 2 * (length + width); }
}

class Triangle extends Shape {


double side1, side2, side3;
public Triangle(double s1, double s2, double s3) {
side1 = s1; side2 = s2; side3 = s3;
}
@Override
public double area() { // Heron's formula
double s = (side1 + side2 + side3) / 2;
return [Link](s * (s-side1) * (s-side2) * (s-side3));
}
@Override public double perimeter() { return side1 + side2 + side3; }
}

3.3 Polymorphic Arrays & Method Parameters


// Array of abstract type – holds any concrete Shape
Shape[] shapes = { new Circle(5), new Rectangle(4, 6), new Triangle(3, 4, 5) };

for (int i = 0; i < [Link]; i++) {


[Link]("Shape " + (i+1) + ":");
displayShapeInfo(shapes[i]); // same method, different runtime types
}

// Method accepting abstract type


public static void displayShapeInfo(Shape s) {
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
}
4. Exception Handling
Java uses try / catch / finally blocks to handle runtime errors gracefully.

4.1 try – catch – Multiple Exception Types


public static void main(String[] args) {
try {
int var1 = [Link](args[0]); // may throw NumberFormatException
int var2 = [Link](args[1]);
int result = var1 / var2; // may throw ArithmeticException
[Link]("result: " + result);

} catch (NumberFormatException e) { // specific exception first


[Link]("Not an integer – please enter an integer");

} catch (ArithmeticException e) { // division by zero


[Link]("Cannot divide by 0");
}
}

4.2 try – catch – finally with File I/O


FileWriter fw = null;
BufferedReader br = null;
try {
fw = new FileWriter("[Link]");
[Link]("Hello opp teacher");
br = new BufferedReader(new FileReader("[Link]"));
[Link]();

} catch (IOException e) {
[Link]("Error catched");

} finally { // always executed – good place to close resources


try {
if (fw != null) { [Link](); [Link]("File closed"); }
if (br != null) {
String line;
while ((line = [Link]()) != null) [Link](line);
[Link]();
}
} catch (IOException e) {
[Link]("Error catched");
}
}
5. File I/O
The repo uses classic [Link] streams as well as the newer [Link] channels for file operations.

5.1 FileWriter / FileReader / BufferedReader


import [Link].*;

FileWriter fw = new FileWriter("[Link]"); // write text


[Link]("Hello");
[Link]();

FileReader fr = new FileReader("[Link]"); // read char-by-char


BufferedReader br = new BufferedReader(fr); // buffered – line-by-line

String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();

5.2 NIO FileChannel + ByteBuffer (TP8/[Link])


import [Link].*;
import [Link];
import [Link];

FileInputStream fis = new FileInputStream("[Link]");


FileOutputStream fos = new FileOutputStream("[Link]");

FileChannel sourceChannel = [Link](); // NIO channel


FileChannel destChannel = [Link]();

ByteBuffer buffer = [Link](1024); // allocate buffer

while ([Link](buffer) > 0) {


[Link](); // switch from write-mode to read-mode
[Link](buffer);
[Link](); // prepare for next read
}

[Link](); [Link]();
[Link](); [Link]();

5.3 Serialization – ObjectOutputStream / ObjectInputStream (TP8)


import [Link].*;

public class Departement implements Serializable { // must implement Serializable


String departmentName;
DepartmentType type;

enum DepartmentType { rh, si } // enum inside class

class Employee implements Serializable {


int id; String name;
public Employee(String name, int id) { [Link]=name; [Link]=id; }
public String toString() { return name + " " + id; }
}
}

// Writing objects to file


ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("[Link]"));
[Link](d); // serialize object
[Link](e);
[Link]();

// Reading objects back


ObjectInputStream in = new ObjectInputStream(
new FileInputStream("[Link]"));
Departement d2 = (Departement) [Link](); // cast required
[Link] e2 = ([Link]) [Link]();
[Link]();

5.4 Anonymous Inner Class implementing Runnable (TP8/exo2)


Runnable task = new Runnable() { // anonymous class
@Override
public void run() {
try {
int character;
while ((character = [Link]()) != -1) {
[Link](character);
}
[Link](); [Link]();
} catch (IOException e) { [Link](); }
}
};
[Link]();
6. Arrays
TP7 exercises cover array creation, traversal, copying, sorting and binary search using [Link]
and [Link].

6.1 Declaring & Initialising an Array with Random Values


import [Link];

int[] tab = new int[10]; // fixed-size array of primitives


Random rand = new Random();
for (int i = 0; i < [Link]; i++) {
tab[i] = [Link](100) + 1; // random int in [1, 100]
}

6.2 Traversal
// Classic for loop with index
for (int i = 0; i < [Link]; i++) {
[Link]("tab[" + i + "] = " + tab[i]);
}

6.3 Copy with [Link]


int[] copie = new int[[Link]];
[Link](original, 0, copie, 0, [Link]);
// args: src, srcPos, dest, destPos, length

[Link]([Link](original)); // pretty-print array


[Link]([Link](original, copie));

6.4 Sort & Binary Search


import [Link];

int[] trie = [Link](); // shallow copy via clone()


[Link](trie); // in-place sort (ascending)

int index = [Link](trie, 50); // requires sorted array


if (index >= 0) [Link]("Found at index " + index);
else [Link]("Not found");
7. Collections Framework
TP7 uses List, Set, and Map from [Link], along with generic type parameters and iterators.

7.1 ArrayList (List allows duplicates, ordered)


import [Link].*;

List<String> liste = new ArrayList<>( // generic type <String>


[Link]("apple","banana","cherry","apple","banana")
);
[Link]("date"); // add element
[Link](liste); // sort in-place
[Link](liste);

7.2 HashSet (Set – no duplicates, unordered)


Set<Integer> ensemble = new HashSet<>(
[Link](10, 20, 30, 10, 20) // duplicates silently ignored
);
boolean added = [Link](30); // returns false – already present
[Link](10);
[Link](ensemble);

7.3 TreeSet (sorted Set)


TreeSet<String> treeChaines = new TreeSet<>(
[Link]("apple","banana","cherry","apple")
);
[Link]([Link]()); // first element alphabetically
[Link]([Link]()); // last element

7.4 HashMap (key → value)


Map<String, Integer> map = new HashMap<>();
[Link]("apple", 1);
[Link]("banana", 2);
[Link]("cherry", 3);
[Link]("date", 4); // add / overwrite entry

[Link]([Link]("cherry")); // true
[Link]([Link]("cherry")); // 3

// Iterate over entries


for ([Link]<String, Integer> e : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}

7.5 Iterator
// Generic iterator – works on any Iterable
Iterator<Integer> it = [Link]();
while ([Link]()) {
[Link]([Link]());
}

// For-each (syntactic sugar for iterator)


for (String s : liste) {
[Link](s);
}
8. Quick-Reference: All Syntax at a Glance

Syntax / Keyword Where used in repo Purpose

class / public class All TPs Define a class

extends TP3, TP4, TP5 Single inheritance

TP5
abstract class / abstract method Template class – force overriding

@Override TP3–TP5 Declare method override

super(…) / [Link]() TP3, TP4 Call parent constructor / method

[Link] All TPs Disambiguate instance field

private / protected / public All TPs Access modifiers

implements Serializable TP8 Mark class for serialization

enum TP8 Enumeration type

new / constructor All TPs Object instantiation

[Link] / [Link] / Math.PITP2, TP4, TP5 Static math utilities

[Link] / print All TPs Standard output

[Link] TP6 String → int conversion

try / catch / finally TP6, TP8 Exception handling

throw / throws TP6 (implicit) Propagate exceptions

TP6, TP8/ ArithmeticException


IOException / NumberFormatException Exception types

import [Link].* TP6, TP8 File I/O classes

TP6
FileWriter / FileReader / BufferedReader Text file streams

TP8
FileInputStream / FileOutputStream Binary file streams

TP8
ObjectOutputStream / ObjectInputStream Object serialization

FileChannel / ByteBuffer (NIO)TP8 High-performance file copy

Runnable / anonymous class TP8 Define a task inline

int[] / new int[n] / .length TP7 Primitive array

TP7
[Link] / [Link] Sort & search arrays

TP7
[Link] / [Link] Array utilities

[Link] / .clone() TP7 Array copying

Random / nextInt() TP7 Pseudo-random numbers

List<T> / ArrayList<T> TP7 Ordered list, allows duplicates

Set<T> / HashSet<T> TP7 Unordered set, no duplicates

TreeSet<T> TP7 Sorted set

Map<K,V> / HashMap<K,V> TP7 Key-value mapping

[Link] / .get / .containsKey TP7 Map operations

[Link]() TP7 Sort a List


Syntax / Keyword Where used in repo Purpose

Iterator<T> / hasNext / next TP7 Manual collection traversal

TP7
for-each (for T x : collection) Enhanced for loop

[Link] / entrySet() TP7 Iterate map entries

Generics <T> TP7 Type-safe collections


9. TP Learning Map

TP Key Topics Files

TP2 Classes, constructors, private fields, this, Math.* [Link], [Link], [Link], [Link]

TP3 extends, super(), @Override, protected, polymorphism [Link], [Link], [Link], [Link], [Link]

TP4 Deepens TP3 + abstract-ready Shape hierarchy (no abstract


[Link],
yet) [Link], [Link], [Link], [Link], [Link]

TP5 abstract class, abstract methods, polymorphic array, method


[Link]
parameters
(abstract), Circle, Rectangle, Triangle, [Link]

TP6 try-catch (multi), finally, IOException, FileWriter/Reader, [Link],


BufferedReader [Link]

TP7 Arrays, [Link]/binarySearch, ArrayList, HashSet, TreeSet,


[Link],
HashMap,
[Link],
Iterator,
[Link]
for-each, Generics

TP8 Serializable, enum, inner class, NIO channels, ByteBuffer,


[Link],
Runnable (anon [Link],
class), ObjectOutputStream/InputStream
[Link]

Generated from [Link] – all code examples extracted verbatim from the repository.

You might also like