0% found this document useful (0 votes)
3 views7 pages

java basics

The document provides an overview of Java, a high-level, object-oriented programming language known for its portability and security. It covers essential topics such as setting up the development environment, basic program structure, data types, operators, control flow statements, methods, object-oriented programming concepts, exception handling, and basic input/output. Additionally, it includes examples to illustrate the concepts discussed.

Uploaded by

richard kipkoech
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views7 pages

java basics

The document provides an overview of Java, a high-level, object-oriented programming language known for its portability and security. It covers essential topics such as setting up the development environment, basic program structure, data types, operators, control flow statements, methods, object-oriented programming concepts, exception handling, and basic input/output. Additionally, it includes examples to illustrate the concepts discussed.

Uploaded by

richard kipkoech
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 7

1. What Is Java?

Java is a high-level, object‐oriented programming language developed by Sun Microsystems


(now Oracle). It’s known for its portability ("write once, run anywhere"), security, and extensive
standard libraries. Java is used in many fields, from desktop and server applications to mobile
apps and large-scale enterprise systems.

2. Setting Up Your Java Development Environment


Before writing any Java code, you’ll need to install the following:

 Java Development Kit (JDK): Download the latest JDK from Oracle’s website (or use
an OpenJDK distribution). Once installed, set your JAVA_HOME environment variable and
add the bin folder to your system’s PATH.
 Integrated Development Environment (IDE): While you can compile Java code using
the command line, many beginners find it easier to work with an IDE such as Eclipse,
IntelliJ IDEA, or NetBeans.

3. Basic Structure of a Java Program


Every Java program consists of classes, and execution begins with the main method. Here’s a
simple “Hello World” example:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

 Class Declaration: Every program is defined within a class. In this example, the class is
HelloWorld.
 Main Method: The JVM starts execution from the main method. It must be declared as
public static void main(String[] args).

4. Variables and Data Types


Java has two broad categories of data types:

Primitive Data Types - specify the size and type of variable values
 byte: 8-bit integer.
 short: 16-bit integer.
 int: 32-bit integer.
 long: 64-bit integer.
 float: Single-precision 32-bit floating-point.
 double: Double-precision 64-bit floating-point.
 char: 16-bit Unicode character.
 boolean: true or false.

Example:

int age = 25;


double salary = 50000.50;
char grade = 'A';
boolean isJavaFun = true;

Reference Types

 Objects: Instances of classes.


 Arrays: Collections of elements of a specific type.

Example:

String greeting = "Hello, Java!";


int[] numbers = {1, 2, 3, 4, 5};

5. Operators
Java supports several types of operators:

 Arithmetic Operators: +, -, *, /, %
 Assignment Operators: =, +=, -=, etc.
 Comparison Operators: ==, !=, >, <, >=, <=
 Logical Operators: &&, ||, !

Example:

int a = 10;
int b = 3;
int sum = a + b; // 13
boolean result = (a > b) && (b < 5); // true
6. Control Flow Statements
Conditional Statements

 if/else: Execute code based on a condition.


 switch: Select among multiple choices.

int score = 90;


if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 80) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}

Loops

 for loop: Ideal for iterating a known number of times.


 while loop: Runs as long as the condition remains true.
 do-while loop: Executes at least once before checking the condition.

Example:

java
.
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}

int j = 0;
while (j < 5) {
System.out.println("Iteration " + j);
j++;
}

7. Methods
Methods (or functions) are blocks of code that perform a specific task. They can accept
parameters and return values.

Example:

java
.
public class Calculator {
// A method that adds two integers and returns the result
public int add(int x, int y) {
return x + y;
}

public static void main(String[] args) {


Calculator calc = new Calculator();
int result = calc.add(5, 3);
System.out.println("Sum is: " + result);
}
}

8. Object-Oriented Programming (OOP)


Java is fundamentally object-oriented. Key concepts include:

Classes and Objects

 Class: A blueprint that defines attributes (fields) and behaviors (methods).


 Object: An instance of a class.

Example:

java
.
public class Person {
// Attributes
String name;
int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Method
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Person person = new Person("Alice", 30);
person.displayInfo();
}
}

Inheritance

Allows one class to inherit fields and methods from another.

java
.
public class Student extends Person {
int studentId;

public Student(String name, int age, int studentId) {


super(name, age);
this.studentId = studentId;
}

public void displayStudentInfo() {


displayInfo(); // inherited method
System.out.println("Student ID: " + studentId);
}
}

Polymorphism

Refers to the ability of a variable, function, or object to take on multiple forms. For instance, a
method in a superclass can be overridden in a subclass.

Encapsulation

Encapsulation means keeping the data (fields) and the code (methods) safe from outside
interference and misuse. This is often achieved by using private fields and public getter/setter
methods.

Abstraction

Abstraction hides complex implementation details and shows only the necessary features of an
object.

9. Packages and Import Statements


Packages help group related classes and avoid naming conflicts. For example:

java
.
package com.example.myapp;

public class MyClass {


// Class content here
}

You can import classes from other packages using the import statement:

java
.
import java.util.ArrayList;
public class Example {
ArrayList<String> list = new ArrayList<>();
}

10. Exception Handling


Exceptions are runtime errors that can be caught and handled using a try-catch-finally
block.

java
.
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This block executes regardless of an
exception.");
}
}
}

11. Basic Input/Output


For console input and output, Java provides classes like Scanner and System.out.

Example using Scanner:

java
.
import java.util.Scanner;

public class InputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}

12. Putting It All Together


Here’s a small program that uses several of the above concepts:
java
.
import java.util.Scanner;

public class UserInfo {


// A method to greet the user
public static void greet(String name) {
System.out.println("Welcome, " + name + "!");
}

public static void main(String[] args) {


// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

// Greet the user


greet(name);

// Example of a loop and condition


System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}

scanner.close();
}
}

You might also like